Shortcode Output Appearing On Top of Post Content in WordPress

While browsing WordPress support forums, I often see threads where users are asking the question ‘Why my shortcode output jumps to the top of the page content?’. Users asking this question are using a shortcode which outputs something and instead of appearing at the exact position where shortcode is placed, their shortcode output appears above rest of the post content.

The problem is actually very simple. The function executed by shortcode should return the output instead of echoing it.

Example of a shortcode using echo to display output:

[php]
function bad_shortcode_function($atts, $content = null) {
echo ‘<p>This is the output of shortcode</p>’;
}
add_shortcode(‘bad-shortcode’, ‘bad_shortcode_function’);
[/php]

The code displayed above would echo the given output but when you add more content to the post or page where shortcode is placed this echo will not appear where the shortcode is placed. The correct way to use shortcodes is to use return. Like this:

[php]
function good_shortcode_function($atts, $content = null) {
$string = ‘<p>This is the output of shortcode</p>’;
return $string;
}
add_shortcode(‘good-shortcode’, ‘good_shortcode_function’);
[/php]

Now if you want to output multiple lines of HTML you can add multiple lines to your output string like this:

[php]
function good_shortcode_function($atts, $content = null) {
$string = ‘<p>This is the output of shortcode</p>’;
$string .= ‘<p>This is the second line of output appended to the first string</p>’;
$string .= ‘<p>And the third line</p>’;
return $string;
}
add_shortcode(‘good-shortcode’, ‘good_shortcode_function’);
[/php]

Hopefully this will help some new plugin developers and WordPress users who are trying their hands on shortcode for the first time. PS: if you recently worked on some awesome shortcode, please feel free to share the snippet below.