Setting up the WordPress shortcode handler function to return echoed strings

Knowledge Base on June 30th, 2010 Comments Off on Setting up the WordPress shortcode handler function to return echoed strings

This post was originally published at on 2009/02/26

Recently I started developing and enhanced version of an existing WordPress plugin. One of my tasks was to add a shortcode function.

The problem: The plugin output was appearing at the top of the page/post, and not where I was placing the shortcode. My main plugin function was echoing quite a few lines. The WordPress shortcode API explicitly states that :

“The return value of a shortcode handler function is inserted into the post content output in place of the shortcode macro. Remember to use return and not echo – anything that is echoed will be output to the browser, but it won’t appear in the correct place on the page.” Source:

It took me a while to discover this as I did not carefully read the description. Lesson 1: Carefully read the documentation.

I experimented for some time trying different alternatives, whatever I could think of from my Fortran/Matlab background, but nothing would would work.

My original setup was this:

function my_func_shortcode($atts) {


add_shortcode('myfunc', 'my_func_shortcode');

my_func_plugin() echoes multiple strings.

The solution: Capture the output buffer with in the shortcode handler function and return it.

The working shortcode function looks like this:

function my_func_shortcode($atts) {



$output_string = ob_get_contents();


return $output_string;
add_shortcode('myfunc', 'my_func_shortcode');

For once again Google proved to be a valuable ally. I found the solution just by searching “capture output php”.

I hope this will be helpful for some of you and save you hours of searching.

Comments are closed.
RSS Feed
on facebook