Wordpress using echo vs return in shortcode function

kabirbaidhya picture kabirbaidhya · Feb 3, 2014 · Viewed 26.6k times · Source

I just noticed, both echo and return works fine for displaying content from a shortcode function in wordpress.

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

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

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

Answer

Nathan Dawson picture Nathan Dawson · Feb 3, 2014

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:

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.

http://codex.wordpress.org/Function_Reference/add_shortcode#Notes