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?
If you are outputting a lot of contents, then you should use:
Its not that echo and return are the same thing.. it's just that once the echo completes in your first function there is nothing left to do... so it returns..
In the second fx your are explicitly exiting the function and returning the value back to the calling function.
If you use "echo" in the shortcode, the information will show up wherever the shortcode is processed, which isn't necessarily where you actually added the shortcode. If you use "return", the information will return exactly where you added the shortcode within the page.
For example, if you have an image, then shortcode, then text:
Echo: will output above the image
Return: will output after the image and before the text (where you actually added the shortcode)
The difference is that
echo
sends the text directly to the page without the function needing to end.return
both ends the function and sends the text back to the function call.For echo:
For return:
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 note from the codex on shortcodes:
http://codex.wordpress.org/Function_Reference/add_shortcode#Notes
I would use:
It is easier when you're doing things like:
Later on..