Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created January 10, 2014 21:31
Show Gist options
  • Save wpscholar/8363040 to your computer and use it in GitHub Desktop.
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.
<?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