Site logo

Archived topic

Remove subheadings (H2) from excerpts

5 replies · Started by Joey on July 17, 2020

Viewing posts 1–6 of 6

Is there a way to automatically remove the subheadings (i.e. H2) from excerpts on the archive and category pages? I know I can just do a custom excerpt but when I do that it screws up my formatting because my featured post has a longer excerpt. I'm not sure if there's a solution for this. I thought I would ask, however, as it looks a little weird. Many of my posts have subtitles and the excerpts by default just display them as a part of the paragraph. Thank you.

Hey it works. This is what I used, in case it helps anyone else:

function bac_wp_strip_header_tags( $text ) {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        //Retrieve the post content.
        $text = get_the_content(''); 
        //remove shortcode tags from the given content.
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
     
        //Regular expression that strips the header tags and their content.
        $regex = '#(<h([1-6])[^>]*>)\s?(.*)?\s?(<\/h\2>)#';
        $text = preg_replace($regex,'', $text);
     
        /***Change the excerpt word count.***/
        $excerpt_word_count = 20; //This is WP default.
        $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);
         
        $excerpt = wp_trim_words( $text, $excerpt_length, $excerpt_more );
        }
        return apply_filters('wp_trim_excerpt', $excerpt, $raw_excerpt);
}
add_filter( 'get_the_excerpt', 'bac_wp_strip_header_tags', 5);
?>

The settings I already have for word count override whatever number I put in for the word count in the code above, which is fine for my purposes. It also overrides anything I write for custom excerpts, which is also fine. Thanks a lot for your help.

Awesome - glad to be of help and thanks for sharing your method.

Joey, David - this is great, and what I needed.

Quick question - what do I add or remove to the code in order to keep the words 'Read more' at the end of the excerpt?

Thank you!

Looks like you already did it?

I'm not seeing Read more on the page you've linked.

If not please open a new topic for the new question.

Thanks!

This archived topic is closed to new replies.