[Resolved] Remove subheadings (H2) from excerpts

Home Forums Support Remove subheadings (H2) from excerpts

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1367379
    Joey

    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.

    #1367615
    David
    Staff
    Customer Support
    #1368221
    Joey

    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.

    #1368468
    David
    Staff
    Customer Support

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

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.