Unwrap Images from Paragraph Tags

Unwrap Images from Paragraph Tags


How to remove the paragraph tags (<p></p>) 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 images (<img>) that are added into a content block with a set of paragraph tags. This can be a pain when you are looking to float or align an image to a different area via CSS.

Warning / Bugs

If you use the following piece of code to resolve the problem you will need to make sure each image is wrapped in the paragraph tag or paragraph and anchor tag and not groups of images in one paragraph tag with a number of returns tags or spaces between each image tag.

Solution

To resolve the paragraph tag being wrapped around an image in the content block 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 filter_ptags_on_images($content) {

	return preg_replace('/<p>\s*()?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', "\1\2\3", $content);

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

Code Breakdown

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

Benefits

The benefits of this method over some alternative solutions such as Javascript is that it is 100% SEO friendly and will not impact on your frontend code. It allows full flexibility to users who are not web savvy who want to still add images via the WUSIWYG editor and the code also considers anchor tags wrapping the images and keeps the anchor tags within the code when the frontend loads.

Plugin Alternative

The WordPress website has a plugin alternatively to this code but I wouldn’t recommend using it. It provides a very unstable and dirty solution to fixing the issue.