Skip to content

Instantly share code, notes, and snippets.

@ashsaraga
Created January 31, 2018 22:44
Show Gist options
  • Save ashsaraga/de5ba068347b8f7e424935a1eb90aa8d to your computer and use it in GitHub Desktop.
Save ashsaraga/de5ba068347b8f7e424935a1eb90aa8d to your computer and use it in GitHub Desktop.
<?php
function custom_excerpt($custom_excerpt__arg) {
global $post;
$raw_excerpt = $custom_excerpt__arg;
if ( '' == $custom_excerpt__arg ) {
$custom_excerpt__arg = get_the_content('');
$custom_excerpt__arg = strip_shortcodes( $custom_excerpt__arg );
$custom_excerpt__arg = apply_filters('the_content', $custom_excerpt__arg);
$custom_excerpt__arg = str_replace(']]>', ']]>', $custom_excerpt__arg);
// runs function to only allow certain tags in the excerpt
// $custom_excerpt__arg = strip_tags($custom_excerpt__arg, custom_excerpt__allowedtags());
// set the excerpt word count and only break after sentence is complete
$excerpt_word_count = 60;
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);
$tokens = array();
$excerptOutput = '';
$count = 0;
// parse the excerpt into tokens; HTML tags, or words, followed by any whitespace
preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $custom_excerpt__arg, $tokens);
// function to find and include the rest of a sentence if the excerpt ends mid-sentence
foreach ($tokens[0] as $token) {
if ($count >= $excerpt_word_count && preg_match('/[\?\.\!]\s*$/uS', $token)) {
// limit reached, continue until , ; ? . or ! occur at the end
$excerptOutput .= trim($token);
break;
}
$count++; // add words to complete sentence
$excerptOutput .= $token; // append what's left of the token
}
$custom_excerpt__arg = trim(force_balance_tags($excerptOutput)); // update excerpt to complete sentences
/*
// set output at the end of the excerpt
$excerpt_end = '<a class="read-more" alt= "' . get_the_title() . '" href="'. esc_url( get_permalink() ) . '">' . sprintf(__( 'Read more >' ), get_the_title()) . '</a>';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
$pos = strrpos($custom_excerpt__arg, '</');
if ($pos !== false) {
$custom_excerpt__arg = substr_replace($custom_excerpt__arg, $excerpt_end, $pos, 0); // inside last HTML tag, add $excerpt_end next to last word
} else {
$custom_excerpt__arg .= $excerpt_end; // after the excerpt content, add $excerpt_end in new paragraph
}*/
return $custom_excerpt__arg;
}
return apply_filters('custom_excerpt', $custom_excerpt__arg, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_excerpt');
function custom_excerpt__allowedtags() {
// tags allowed in the excerpt when custom_excerpt() is called
return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>,<strong>,<pre>,<blockquote>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment