Turn a snippet of HTML and PHP into a shortcode

the code is

<div class="huili-relevant-left">
                    <a href="<?php echo get_post_meta($post->ID,"taobao_value",true);?>" hidefocus="true" target="_blank" class="btn-buy js-log " data-log="page=p-huihui-discount-detail&type=buy">
                        <b>ï¿¥<?php echo get_post_meta($post->ID,"price_value",true);?></b>
                        <i>buy</i>
                    </a>
                </div>

the has two Custom Fields is taobao_value and price_value
now I want become a shortcode
Please help me

Related posts

1 comment

  1. When you want to turn a snippet into a shortcode, you have to return a string. You cannot use echo or print anything in any other way.

    Also, always escape your data, and check if there are actually values.

    I have used the HEREDOC syntax here, because it is easy to read:

    add_shortcode( 'taobao', 'taobao_shortcode' );
    
    function taobao_shortcode()
    {
        $taobao = esc_attr( get_post_meta( $post->ID, "taobao_value", true ) );
        $price  = esc_html( get_post_meta( $post->ID, "price_value", true ) );
    
        if ( ! $taobao or ! $price )
            return;
    
        return <<<SHORTCODE
        <div class="huili-relevant-left">
            <a href="$taobao" 
                hidefocus="true" 
                target="_blank" 
                class="btn-buy js-log" 
                data-log="page=p-huihui-discount-detail&type=buy"
            >
                <b>ï¿¥ $price</b>
                <i>buy</i>
            </a>
        </div>
    SHORTCODE;
    }
    

    You can insert the value into your posts now with [taobao].

Comments are closed.