Custom Shortcode for Excerpt that includes HTML tags

This code creates a custom shortcode that can be used instead of an excerpt.  The features of it are:

  • Specify the length in words
  • It will count to the chosen length in words, and then output more words until the next end of sentence punctuation (. ! ? 😉
  • It allows HTML tags to be included and closes them to make sure the site doesn’t break.
// Get custom excerpt including tags - length in words not characters.
function custom_excerpt_function ( $atts = '' ) {
$value = shortcode_atts( array(
'length' => '',
), $atts );

$post = get_post();
$wpse_excerpt = $post->post_content;
$wpse_excerpt = strip_shortcodes( $wpse_excerpt );
$wpse_excerpt = apply_filters('the_content', $wpse_excerpt);
$wpse_excerpt = str_replace(']]>', ']]>', $wpse_excerpt);
$wpse_excerpt = strip_tags($wpse_excerpt, '<a>,<blockquote>,<br>,<em>,<i>,<ul>,<ol>,<li>,<p>,<img>'); /* to allow just certain tags. Delete if all tags are allowed */

//Set the excerpt word count and only break after sentence is complete.
$excerpt_length = $value['length'];
$tokens = array();
$excerptOutput = '';
$count = 0;
// Divide the string into tokens; HTML tags, or words, followed by any whitespace
preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $wpse_excerpt, $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;
}

$wpse_excerpt = trim(force_balance_tags($excerptOutput));
//$wpse_excerpt = $post->post_content;

return $wpse_excerpt;

}
add_shortcode("custom_excerpt", "custom_excerpt_function");

Usage:

[custom_excerpt length="150"]
Share This