Omit image captions from get_the_content()

I use a theme that calls get_the_content() to display short excerpts of the latest blog posts on the home page. Now I noticed that the excerpt sometimes starts with an image caption, if the blog post contains a picture at the very beginning. I usually do that and make the text float around it.

I always set the first three caption fields on an image (Alt Text, Title, Caption).

Is there any way to strip these image captions from the return value of get_the_content() or is there any other method that I could possibly call instead? I checked the documentation, but there seems no argument to exclude images from the return value.

Topic the-content captions images Wordpress

Category Web


It turned out that the method called strip_tags(preg_replace(" (\[.*?\])", '', $output)) before strip_shortcodes($output), which caused aforementioned issue, since the code removed shortcode in square brackets, but retained contained image captions.

I could fix it by swapping the two method calls like this:

$output = get_the_content();
$output = strip_shortcodes($output); // Strip WordPress shortcodes first!
$output = strip_tags(preg_replace(" (\[.*?\])", '', $output));

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.