Support » Themes and Templates » Custom Excerpts Not Ending HTML Tags

  • I’m trying to add custom automatic excerpts so I can include HTML tags and control the length, etc. but for some reason my code is causing issues with the read more button. The last HTML tag before the Read More button is not getting stripped, and instead, the button becomes part of that tag.

    For example, if there is a list before the button, the button becomes part of the list; another example, I have an H2 tag starting in the editor so there’s a beginning h2 tag, then the button shows within the H2 tag, as if it’s part of it.

    Hard to explain, but here is my code in the functions.php file. Maybe someone with more experience can see what I’m doing wrong? I can’t remember where I got this code from I’ve been using it for a long time but after I added more HTML tags to the list, it started causing issues.

    function custom_wp_trim_excerpt($text) {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        //Retrieve the post content. 
        $text = get_the_content('');
        //Delete all shortcode tags from the content. 
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $allowed_tags = '<p>,<b>,<strong>,<em>,<i>,<a>,<h2>,<br><br />,<blockquote>,<img>,<ul>,<li>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/
        $text = strip_tags($text, $allowed_tags);
        $excerpt_word_count = 65; /*** MODIFY THIS. change the excerpt word count to any integer you like.***/
        $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 
        $excerpt_end = '[...]<br /><br /><a href="'. get_permalink($post->ID) . '" class="button">Continue Reading</a>'; /*** MODIFY THIS. change the excerpt end to something else.***/
        $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
        $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
        if ( count($words) > $excerpt_length ) {
            $text = implode(' ', $words);
            $text = $text . $excerpt_more;
        } else {
            $text = implode(' ', $words);
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
    remove_filter('get_the_excerpt', 'wp_trim_excerpt');
    add_filter('get_the_excerpt', 'custom_wp_trim_excerpt');

    Thanks for your help 🙂

  • The topic ‘Custom Excerpts Not Ending HTML Tags’ is closed to new replies.