How to return a string that has a variable inside in a shortcode?

When you want to return a data combined with a string, you can use one of the following methods:

Either open and close the string using ':

return '<span class="class2" id="class3-' . $random . '"> </span>';

Or use the double quote:

return "<span class="class2" id='class3-{$random}'> </span>";

You can simply use $random without the {} curly brackets, but it’s easier to read if you use {}.

You can even use double quotes for the inner string, but you need to escape them:

return "<span class=\"class2\" id=\"class3-{$random}\"> </span>";

As pointed out in comments by @birgire, to make it more WordPressy, we can also escape the variable:

return sprintf( '<span class="class2" id="class3-%s"></span>', esc_attr( $random ) );

Leave a Comment