Unwrap Shortcode from Paragraph Tags

Unwrap Shortcode from Paragraph Tags


Removing Paragraph tags from around shortcodes which are automatically added by the TinyMCE editor in WordPress. This article will help explain how to remove these unwanted paragraph tags when your website renders for frontend users. Which can be incredibly frustrating when styling your website with your own theme.

Issue

The content editor in WordPress pre-wraps any shortcodes that are added into a content block with a set of paragraph tags. This will invalidate your code and also cause your CSS to generate your website in the correct visual way.

Solution

The following piece of code will resolve the problem. You will need to add the following lines of code to your theme function file. This can be modified in the theme editor (editor) section under the Appearance menu option in the WordPress admin area.

Code

function dino_clean_shortcodes($content) {

	$content = strtr($content, ['[' => '[',']' => ']',']' => ']']);
	return $content;

}
add_filter('the_content', 'dino_clean_shortcodes');

Code Breakdown

What this code does it cleans the content during the loading of the page.

Benefits

The benefits of adding this code is it makes your code SEO friendly, keeps your code valid and the visual appearance of your theme correct when adding additional functionality to your WordPress site. It allows full flexibility to users who are not web savvy who are using the WYSIWYG editor to insert Shortcodes into pages and posts.