Sometimes when you add WordPress shortcodes in your content, empty paragraph tags are added too!
That’s frustrating. You need to remove those empty p
tags to prevent your content from being distorted. I had it happen enough that I decided to do something about it. I created a quick code snippet to remove those empty paragraph tags from shortcodes on my own WordPress site, and I thought it would be nice to share it with you as well!
Simply drop the following code in your theme’s functions.php
file:
/**
* Removes empty paragraph tags from shortcodes in WordPress.
*/
function tg_remove_empty_paragraph_tags_from_shortcodes_wordpress( $content ) {
$toFix = array(
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']'
);
return strtr( $content, $toFix );
}
add_filter( 'the_content', 'tg_remove_empty_paragraph_tags_from_shortcodes_wordpress' );
That’s it! All empty paragraph tags have been removed from your shortcodes.
If you’ve found this content helpful, please share it with others! You can do so by clicking on one of the social sharing buttons in this article.
Matt
This worked for me! Thanks for posting this trick!
Thomas Griffin
You bet, Matt! Glad it removed those empty paragraph tags for you. 🤩
Daniel
Thank you, this has been in my to do list for too long!
It works!
One question: why the “” in the code?
Daniel
*** Amend ***
One question: why the — br — in the code?
Thomas Griffin
Hey Daniel – it’s there because sometimes line breaks can also cause extra space to be added which “feel” like the space added by empty paragraph tags, so I chose to remove them as well.
Klaas Koopman
Hi Thomas,
Am I right by saying this doesn’t work anymore?
Thomas Griffin
Hey Klaas – no, this does in fact still work and achieves the result you would be looking for. 🙂