Last active
December 18, 2015 16:19
-
-
Save allanemerson/5810266 to your computer and use it in GitHub Desktop.
Wordpress's excerpts kinda suck to customize. This function allows you to generate an excerpt at a desired word count with an optional "Read More" link. It also trims the result back to the last complete sentence to keep things pretty.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function custom_excerpt($limit = 55, $more = false){ | |
// from wp_trim_excerpt() in /wp-includes/formatting.php | |
$text = get_the_content(''); | |
$text = strip_shortcodes( $text ); | |
$text = apply_filters('the_content', $text); | |
$text = str_replace(']]>', ']]>', $text); | |
// wp already has a trim function | |
$text = wp_trim_words($text, $limit, ''); // pass an empty string in as $more, so we can define our own | |
// let's trim this back to the last sentence | |
$punctuation_locations = array( | |
strrpos($text, '.', -1), | |
strrpos($text, '?', -1), | |
strrpos($text, '!', -1), | |
strrpos($text, ')', -1), | |
strrpos($text, '"', -1) | |
); | |
$pos = max($punctuation_locations); | |
if($pos != false) { | |
$text = substr($text, 0, $pos+1); | |
} | |
// tack on the read more if asked to | |
if( $more ){ | |
$text .= ' <a href="'.get_permalink().'" title="'.get_the_title().'">Read more...</a>'; | |
} | |
return wpautop($text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment