$output = '<p class="one"><small>'.$newsletter_one. '</small></p>'

Generally, when we write short codes we publish HTML like the above one, and instead of echo use return function.

How should we write this one →

<span class="class2" id="class3-<?php echo $random;?>"> </span>

Like this →

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

or does this has some flaws?


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 ) );
  • Ok. so this {$random} = . $random . – The WP Intermediate Sep 12 '17 at 7:27
  • 1
    Yes, but only if you wrap your string in double quotes, not single quotes. – Jack Johansson Sep 12 '17 at 7:28
  • 2
    ps: then there's this way: :return sprintf( '<span class="class2" id="class3-%s"></span>', esc_attr( $random.) ); – birgire Sep 12 '17 at 7:41

In addition to Jack Johansson's answer (I'd add a comment to that but it seems I need to have been here longer to do that than to post my own answer!) I don't think you even need the internal double quotes. AFAICT (I'm a relatively recent PHP programmer), you could just write

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

and that would work just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.