How To Remove Auto Generated P Tag Around Images In WordPress With Functions.Php?
April 30th, 2018 in Wordpress |

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.

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.