Turn a snippet of HTML and PHP into a shortcode

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="https://wordpress.stackexchange.com/questions/103984/$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].

Leave a Comment