How to Fix Shortcode Outputs Before Content or Widget Title

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 Outputs Before Content or Widget Title

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

Advertisement

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.

Advertisement

Leave a Reply

Your email address will not be published.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top