Support » Fixing WordPress » How to use echo do_shortcode with dynamic variable?

  • Resolved bryanb55


    I cant seem to figure out how to put a dynamic variable inside a php shortcode here is what I’m trying….

    <?php echo do_shortcode('[walkscore ws_wsid="example" ws_address="SOME PHP HERE"]'); ?>

    The code I’m trying to put where it says “SOME PHP HERE” is:

    <?php echo get_post_meta($post->ID, 'pyre_full_address', true); ?>

    But I cant seem to get the syntax right. I tried wrapping it in {} but no luck…

    What am I doing wrong?


Viewing 4 replies - 1 through 4 (of 4 total)
  • You’re close to right, but this should be what you’re after (note, I haven’t tested this.. it’s just cut-and-paste):

    <?php echo do_shortcode('[walkscore ws_wsid="example" ws_address="'.get_post_meta($post->ID, 'pyre_full_address', true).'"]'); ?>

    If that doesn’t work I’d guess that the get_post_meta() call isn’t working properly, so you could try this for some de-bugging:

    <?php $val = get_post_meta($post->ID, 'pyre_full_address', true);
    echo "<p>Val: '".$val."'</p>";
    echo do_shortcode('[walkscore ws_wsid="example" ws_address="'.$val.'"]'); ?>

    That did it. Thanks!

    I think I can see where you went wrong looking back at it now.

    When you use strings with single-quotes like ‘Hi, ho ware you?’, they are just parsed as they are, nothing is done with them. When you use double-quotes like “Hello, how are you?” the string is parsed to check for variables. As you were using single-quotes, PHP won’t look inside the string to see if there’s any variables in it.

    That’s why I always set any variables or functions or anything else that’s not actually a set part of the string outside of the actual string like I’ve shown.

    echo "There are ".count ($sheep)." sheep.";

    That way it doesn’t matter if you’re using single or double quotes, the values will always work correctly. It also helps readability when you’re using an editor with syntax colouring.

    @michael.mariart Thanks a lot for code.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to use echo do_shortcode with dynamic variable?’ is closed to new replies.