Skip to content

Instantly share code, notes, and snippets.

@chrisblakley
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisblakley/415de5d2f492f441f078 to your computer and use it in GitHub Desktop.
Save chrisblakley/415de5d2f492f441f078 to your computer and use it in GitHub Desktop.
A smarter Wordpress excerpt.
//Use this instead of the_excerpt(); and get_the_excerpt(); so we can have better control over the excerpt.
//Several ways to implement this:
//Inside the loop (or outside the loop for current post/page): nebula_the_excerpt('Read more »', 20, 1);
//Outside the loop: nebula_the_excerpt(572, 'Read more »', 20, 1);
function nebula_the_excerpt( $postID=0, $more=0, $length=55, $hellip=0 ) {
if ( $postID && is_int($postID) ) {
$the_post = get_post($postID);
} else {
if ( $postID != 0 || is_string($postID) ) {
if ( $length == 0 || $length == 1 ) {
$hellip = $length;
} else {
$hellip = false;
}
if ( is_int($more) ) {
$length = $more;
} else {
$length = 55;
}
$more = $postID;
}
$postID = get_the_ID();
$the_post = get_post($postID);
}
if ( $the_post->post_excerpt ) {
$string = strip_tags(strip_shortcodes($the_post->post_excerpt), '');
} else {
$string = strip_tags(strip_shortcodes($the_post->post_content), '');
}
$string = string_limit_words($string, $length);
if ( $hellip ) {
if ( $string[1] == 1 ) {
$string[0] .= '… ';
}
}
if ( isset($more) && $more != '' ) {
$string[0] .= ' <a class="nebula_the_excerpt" href="' . get_permalink($postID) . '">' . $more . '</a>';
}
return $string[0];
}
//Text limiter by words
function string_limit_words($string, $word_limit){
$limited[0] = $string;
$limited[1] = 0;
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit){
array_pop($words);
$limited[0] = implode(' ', $words);
$limited[1] = 1;
}
return $limited;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment