How do I mix php inside php strings?

I’m trying to mix <?php echo do_shortcode('[...]') with a field from Advanced Custom Fields within WordPress.

So basically what I’m trying to do is give the user a text field in the page edit screen where she can paste in the ID of a youtube vide. This field will then update my do_shortcode to display the correct video.

Read More

I’m not sure what I’m doing wrong considering I’ve done this several times before and been succesful. I do have a feeling I’m not escaping the string correctly?

<?php echo do_shortcode('[video_lightbox_youtube video_id="' . the_field("youtube_video") . '" width="640" height="480" anchor="Play Video"]'); ?>

Anyone able to lead me in the right direction? 🙂

EDIT

The code above returns q_cHD1lcEOo with multiple spaces in front of it as well as this: "Error! You must specify a value for the Video ID, Width, Height parameters to use this shortcode!" That’s why I was thinking I’m not escaping it correctly as these are all specified.

I’ll add that if I remove the_field("...") and replace it with just an ID it displays perfectly.

SECOND EDIT

Since I was not supposed to echo it, I was using the wrong function to get the field. Instead of using the_field() which prints the value, I was supposed to use get_field() to simply return it to the string.

Related posts

Leave a Reply

2 comments

  1. Your question is somewhat unclear, but I’m also 20 hours without sleep.

    Anyways, as far as mixing PHP within a PHP string, there’s numerous ways to do it..

    You can use concatenation or { } within the string itself.

    For example, say we want to echo out the property of an object within a string.

    We could do the following

    echo "This is my property " . $object->property;
    

    Or, we can do this

    echo "This is my property {$object->property}";
    

    You can even do cool things like access associative arrays within strings like so

    echo "This is my property {$object->property['cool']}";
    

    Hopefully this leads you in the ride direction.

  2. At first glance it looks like you should be using get_field instead of the_field. the_field will print without being prompted, whereas get_field will return its value, which is what you want.

    I see you’ve also mentioned whitespace at the start, you should consider wrapping the function in trim.

    See below:

    <?php echo do_shortcode('[video_lightbox_youtube video_id="' . trim(get_field("youtube_video")) . '" width="640" height="480" anchor="Play Video"]'); ?>