neilgee
9/2/2016 - 11:30 PM

WP Excerpt - allow HTML Tags in Excerpt

WP Excerpt - allow HTML Tags in Excerpt

<?php

//ref - http://wordpress.stackexchange.com/questions/141125/allow-html-in-excerpt/141136


function wpb_excerpt_allowedtags() {
    // Add custom tags to this string
        return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>'; 
}


function wpb_custom_wp_trim_excerpt($text) {
$raw_excerpt = $text;
    if ( '' == $text ) {

        $text = get_the_content('');
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]&gt;', $text);
        $text = strip_tags($text, wpb_excerpt_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */

        //Set the excerpt word count and only break after sentence is complete.
            $excerpt_word_count = 35;
            $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 
            $tokens = array();
            $excerptOutput = '';
            $count = 0;

            // Divide the string into tokens; HTML tags, or words, followed by any whitespace
            preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $text, $tokens);

            foreach ($tokens[0] as $token) { 

                if ($count >= $excerpt_length && preg_match('/[\,\;\?\.\!]\s*$/uS', $token)) { 
                // Limit reached, continue until , ; ? . or ! occur at the end
                    $excerptOutput .= trim($token);
                    break;
                }

                // Add words to complete sentence
                $count++;

                // Append what's left of the token
                $excerptOutput .= $token;
            }

        $text = trim(force_balance_tags($excerptOutput));

            $excerpt_end = ''; 
            $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 

   
            $text .= $excerpt_more; /*Add read more in new paragraph */

        return $text;   

    }
    return apply_filters('wpse_custom_wp_trim_excerpt', $text, $raw_excerpt);
}



remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpb_custom_wp_trim_excerpt');