Remove Subheadings (H2, H3….) from WordPress Archive Post Excerpt

There are two ways to remove Subheadings from the default WordPress post excerpt. Use either of the codes provided. The first code just removes the headings. You can use theme options to set the excerpt length.

Option 1:

/* Remove Heading Blocks from Excerpt */
function custom_remove_headings_blocks_excerpts( $allowed_blocks ) {
$key = array_search( 'core/heading', $allowed_blocks );
if ( $key !== false ) {
unset( $allowed_blocks[ $key ] );
}
return $allowed_blocks;
}
add_filter( 'excerpt_allowed_blocks', 'custom_remove_headings_blocks_excerpts', 100, 1 );

Source: ConditionalBlocks

Option 2:

In the below code you can also set the excerpt length.

/* Remove Subheadings from Post Excerpt */
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);
        $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);

Source: bacsoftwareconsulting