admin管理员组

文章数量:1200973

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.

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.

Share Improve this question edited May 30, 2022 at 7:27 user1438038 asked Jan 17, 2020 at 18:08 user1438038user1438038 1761 silver badge12 bronze badges 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()? – user1438038 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(); – user1438038 Commented Jan 19, 2020 at 12:25
 |  Show 2 more comments

1 Answer 1

Reset to default 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));

本文标签: the contentOmit image captions from getthecontent()