When it comes to creating and editing content in WordPress, the default behavior of the platform is to wrap images and iframes in paragraph tags. While this may not seem like a big issue, it can actually cause problems with the layout and styling of a website. To combat this, developers can use the WordPress filter system to modify the way that the content is displayed.

One solution to this problem is to use the “img_unautop” function. This function utilizes regular expressions to remove the paragraph tags that wrap around images and iframes.

Removing  <p> tags from images in WordPress

Please add below code in function.php:

function img_unautop($pee) { 
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU',
'\1\2\3', $content);
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
}
 add_filter( 'the_content', 'img_unautop', 30 );

The function starts by defining the regular expression pattern for images. This pattern searches for the opening paragraph tag, followed by any optional elements such as a link tag, then the image tag, and finally the closing paragraph tag. The “iU” flag is used in the regular expression, which makes the pattern matching case-insensitive and also makes the “U” pattern ungreedy.

Once the pattern is defined, the function uses the “preg_replace” function to search the content for the pattern and replace it with the image tag and any optional elements, such as a link tag. This effectively removes the paragraph tags from around the image.

The same process is then repeated for iframes, using a similar regular expression pattern and the “preg_replace” function.

Once the function is defined, it is added as a filter to the “the_content” hook using the “add_filter” function. The “the_content” hook is a built-in WordPress hook that is used to filter the content of a post or page before it is displayed. By adding the “img_unautop” function as a filter to this hook, the function will be applied to the content of the post or page before it is displayed on the front-end of the website.

In summary, the “img_unautop” function is a powerful tool for developers looking to remove the default paragraph tags that wrap around images and iframes in WordPress. By utilizing regular expressions, this function makes the layout and styling of a website much more flexible and efficient.