WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to use echo do_shortcode with dynamic variable? (5 posts)

  1. bryanb55
    Member
    Posted 1 year ago #

    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?

    Thanks!

  2. michael.mariart
    Member
    Posted 1 year ago #

    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.'"]'); ?>
  3. bryanb55
    Member
    Posted 1 year ago #

    That did it. Thanks!

  4. michael.mariart
    Member
    Posted 1 year ago #

    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.

  5. netechx
    Member
    Posted 9 months ago #

    @michael.mariart Thanks a lot for code.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags