WordPress shortcode output buffer versus appending to string

When your develop a WordPress plugin there is a big chance that you will need to include a shortcode. If you simply echo each line, you will notice that your output will not appear on the right place. This is because WordPress will output your code as soon as it encounters the echo. Therefore you should use a different way to get your output on the page. This will ensure that the output will appear on the place where you’ve added the shortcode.

1) You can use the output buffer of PHP, by starting it with ob_start(). Then simply use echo to output your lines. Once you’ve defined your output you can collect your output to a variable, with ob_get_contents() and return this:

function my_shortcode() {
echo 'hello world';
echo 'This is a WordPress shortcode';
$output_string = ob_get_contents();
return $output_string;

This will ensure that all your output will be catched by the output buffer and returned. When using multiple shortcodes on a page, this can cause conflicts.

2) Another option is to append strings, this would mean we would rewrite the code above to:

function my_shortcode() {
$output_string = 'hello world';
$output_string .= 'This is a WordPress shortcode';
return $output_string;

This should solve any problems with the output of your WordPress shortcode appearing on the wrong place.

This entry was posted in Wordpress. Bookmark the permalink.

4 Responses to WordPress shortcode output buffer versus appending to string

  1. Jaume Sala says:

    Thank you, really I didn’t undertand whats happeing 🙂

  2. I had included a wordpress function (bloginfo(‘url’) within my short code function and the first method worked for me, the second would still output in the wrong place but does work fine when returning strings and I suppose regular php functions.

    Many thanks for posting this

    • Rich Berrill says:

      The reason for that is that bloginfo() sends the output directly to the buffer, while get_bloginfo() returns it. get_bloginfo() being added to one of the strings in the second method would be the one you would want to use.

Comments are closed.