2

I'm using WordPress 4.2.2 and every time I add an image to the wysiwyg it wraps the outputed image in a paragraph tag. I need to strip out these tags. Everything I seem to find online is from 2011 plus it doesn't seem to work.

I have tried putting things in the functions.php like:

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');

Nothing seems to work. How can I accomplish this.

BTW I am using ACF Pro's wysiwyg and JointsWP starter theme and my images ARE NOT wrapped in a link tag if that makes a difference.

9

1) Filter wpautop() with ACF:

function filter_ptags_on_images($content) {
    $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('acf_the_content', 'filter_ptags_on_images');
add_filter('the_content', 'filter_ptags_on_images');

If you have both of those try checking with a later priority on the add_filter. It's possible the theme or plugin or acf is overriding you....

add_filter('acf_the_content', 'filter_ptags_on_images', 9999);
add_filter('the_content', 'filter_ptags_on_images', 9999);

2) Edit wpautop():

<?php
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'custom_wpautop' );
function custom_wpautop() {
 // copy wpautop() code at https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L373 and add img to the $allblocks variable
}

3) This above is a lot of code for one task however. Consider trying this: https://wordpress.org/plugins/preserved-html-editor-markup-plus

4) You could try this although not as good as the method you're trying to accomplish since this one is done with javascript.

<script type="text/javascript">
jQuery(document).ready(function($){
    $('p > img').unwrap();
});
</script>

5) if it's just the styling that's messing things up and you don't care about the markup:

<style type="text/css">
p > img {
    margin: 0 !important;
}
</style>
  • The first option works now also for ACF wysiwyg as far as effecting it but it doesn't show any content. Its all blank on the output so I just used the jQuery way. – agon024 Jul 22 '15 at 19:51
  • Glad one of them worked! I have acf installed on a couple of my sites so I'll test it out when I get a chance. – Bryan Willis Jul 29 '15 at 15:52
  • Maybe it doesn't need add_filter('the_content', 'filter_ptags_on_images'); when using add_filter('acf_the_content', 'filter_ptags_on_images'); – Bryan Willis Jul 29 '15 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.