Ad

How To Remove Caption P Class From Wordpress?

- 1 answer

I don't want any images or their captions to appear within my loop, but I want to maintain the styling of the html.

So far I'm able to rid myself of the images using this function:

function remove_images () {
$content = get_the_content();
$content = apply_filters('the_content', $content);
$content = strip_tags($content, '<p><a>');
return $content;
}

Now, since I've kept all <p> tags for styling purposes and to keep written article content, this means the captions for the images are not removed because they're wrapped in <p class="wp-caption-text">

So now, how can I remove just that one class so that the captions don't appear? And I want to write it as a function to call it at specific times. I have multiple loops and in some of them I want the captions and in others I don't...

Ad

Answer

Firstly, rather than the way you're doing this I would use the_content() where you want the content outputted (in your template or wherever you're using this). Then, use add_filter() to modify the content.

Secondly to remove the tag with a class you'll have to use our good old friend regex. So your code might look a bit like this:

function remove_images( $content ){
    if( /*condition for where you want this to occur*/ ){
        $content = strip_tags($content, '<p><a>');
        $content = preg_replace('#<p class="wp-caption-text">(.*?)</p>#', '', $content );
    }
    return $content;
}
add_filter( 'the_content', 'remove_images', 100, 1);
Ad
source: stackoverflow.com
Ad