0

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.

7
  • 1
    have a look at developer.wordpress.org/reference/functions/strip_shortcodes
    – Michael
    Commented Jan 17, 2020 at 18:38
  • 1
    it might be easier to add some CSS to hide img and/or caption tags in the targeted area.
    – majick
    Commented Jan 17, 2020 at 22:01
  • strip_tags() and strip_shortcodes() are applied to the excerpt already, but the image caption is plain text. There is no CSS identifier either. Is there no alternative to get_the_content()? Commented Jan 18, 2020 at 13:23
  • "a theme that calls get_the_content() to display short excerpts of the latest blog posts" - please post the corresponding code
    – Michael
    Commented Jan 19, 2020 at 4:39
  • @Michael: Sure, just for you: $output = get_the_content(); Commented Jan 19, 2020 at 12:25

1 Answer 1

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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