kabirbaidhya kabirbaidhya - 3 months ago 76
PHP Question

Wordpress using echo vs return in shortcode function

I just found out that both 'echo' and 'return' works fine for displaying content from a shortcode function.

function foobar_shortcode($atts) {
echo "Foo Bar"; //this works fine

function foobar_shortcode($atts) {
return "Foo Bar"; //so does this

I just want to know, is there any difference between using either of these? If so what's the recommended one? I normally use echo in this case; is it okay?


Echo may work in your specific case but you definitely shouldn't use it. Shortcodes aren't meant to output anything, they should only return content.

Here's a snippet taken from the codex on shortcodes:

"Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results."