Created
January 10, 2014 21:31
-
-
Save wpscholar/8363040 to your computer and use it in GitHub Desktop.
Generate an excerpt from provided content. Strips HTML, removes trailing punctuation and adds a 'more' string when text has been removed.
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
<?php | |
/** | |
* Get an excerpt | |
* | |
* @param string $content The content to be transformed | |
* @param int $length The number of words | |
* @param string $more The text to be displayed at the end, if shortened | |
* @return string | |
*/ | |
function get_excerpt( $content, $length = 40, $more = '...' ) { | |
$excerpt = strip_tags( trim( $content ) ); | |
$words = str_word_count( $excerpt, 2 ); | |
if ( count( $words ) > $length ) { | |
$words = array_slice( $words, 0, $length, true ); | |
end( $words ); | |
$position = key( $words ) + strlen( current( $words ) ); | |
$excerpt = substr( $excerpt, 0, $position ) . $more; | |
} | |
return $excerpt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment