How to Remove auto generated P Tag Around Images in WordPress with Functions.php?

When you add images to the posts, the paragraph tag is automatically added around the images in WordPress post. You can view the tag in the source code as well.

You can disable this WordPress feature by adding a simple function to your theme’s functions.php file.

Keep in mind normally p tag has some margin-bottom to add some spacing below the paragraph, For example, the twenty-seventeen theme has margin: 0 0 1.5em; for the p element.

How to remove P tag around images in WordPress
Remove P tag around images in WordPress
  1. Login to WordPress Dashboard
  2. Go to Appearance > Editor
  3. Select Theme Functions (functions.php) file.
  4. Add the following function and click update changes.

// Remove P Tags Around Images 
function filter_ptags_on_images($content){
    return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');

That’s all.

Don’t forget to Subscribe to our WORDPRESS YOUTUBE CHANNEL to find more video tutorials


You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *