How to fix WordPress Shortcode Output Before Content or Widget

If you are new to creating WordPress shortcodes, then you may have found this issue. In my early days, I got the same issue and after spending a lot of time on this, I found the solution.

Fix Shortcode Output Before Content or Widget Title

The only reason behind shortcode output before content or widget title is your shortcode callback function “echo-ing” output instead of “return-ing”.

To fix this, all you need to do is, Just check the callback function for your shortcode and use “return” to output instead of “echo”.

To understand better, Let’s see the examples below:


function diwp_our_twitter_link(){

	$output = '<a href="https://twitter.com/myuser">Follow us on Twitter</a>';

	echo  $output;

}

add_shortcode('twitter_link', 'diwp_our_twitter_link');

This will output the result above the page content or widget title, cause I am using echo to display the output.

So to fix this, Instead of using “echo”, I will use “return” to output like in the below code.


function diwp_our_twitter_link(){
	
	$output = '<a href="https://twitter.com/myuser">Follow us on Twitter</a>';	
	
	return $output;

}

add_shortcode('twitter_link', 'diwp_our_twitter_link');

Isn’t it super easy?… Obviously Yes.

Owner of diveinwp.com, solely responsible for creating helpful, informative content about WordPress, a fulltime WordPress developer with 8+ years of hands-on experience in WordPress design and development.