How to insert php variable into Wordpress shortcode?

I am setting up custom fields in Wordpress to be able to enter ASIN number from amazon and go through the shortcode I have in my template file.

In my custom field I am using Name: asin and Value: (whatever ASIN # I want to add)

This is what I have in my template file:

<?php $asin = get_post_meta( $post->ID, 'asin', true); ?>

<?php echo $asin ?>

<?php echo do_shortcode( '[scrapeazon asin="B002P4SMHM" width="650" height="400" border="false" country="us")]' );?>


I am trying to put the $ asin variable in the scrapeazon shortcode I have, something like this:

<?php echo do_shortcode( '[scrapeazon asin="<?php echo $asin ?" width="650" height="400" border="false" country="us")]' );?>


But it doesn't work, no ideas?


source to share

1 answer

How about this approach?

function my_shortcode_function( $attributes ) {
    global $post;

    // manage attributes
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $attributes );

    // do sth with the custom field
    $asin = get_post_meta( $post->ID, 'asin', true);

add_shortcode('my_shortcode', 'my_shortcode_function');


So don't try to get a custom value in the template. Just handle it in the shortcode function. Through the $ post global declared variable it should work. Yes, the global ist is not very clean. But this is wordpress ...



All Articles