简体   繁体   中英

How do I insert a php variable into a Wordpress shortcode?

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

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

Here is what I have currently in the 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 variable $asin into the scrapeazon shortcode that I have, something like this:

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

But this is not working, any ideas?

What 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 the custom value in the template. Just deal with it in the shortcode function. Through the global declared $post variable it should work. Yes, global ist not very clean. But it 's wordpress ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM