Skip to content

Instantly share code, notes, and snippets.

@WPDevHQ
Created December 7, 2016 17:32
Show Gist options
  • Save WPDevHQ/05c9ec05fc42c248f1297738869295dc to your computer and use it in GitHub Desktop.
Save WPDevHQ/05c9ec05fc42c248f1297738869295dc to your computer and use it in GitHub Desktop.
Perfect Excerpts for WordPress
// if you're tired of excerpts cutting in half, here it is, the perfect solution
// that shortens your excerpt to full sentences in your characters limit.
<?php
function perfect_excerpt( $length ) {
$excerpt = get_the_excerpt($post->ID);
$short_excerpt = substr($excerpt, 0, $length);
// look for the last period
$finishline = strrpos( $short_excerpt, '.');
// period not found, check for question mark
if (empty($finishline)) {
$finishline = strrpos( $short_excerpt, '?');
}
// question mark also not found, search for exclamation mark
if (empty($finishline)) {
$finishline = strrpos( $short_excerpt, '!');
}
// now we need check if there are really long first sentences
// that don't have periods, exclamation or question mark
// in our characters limit
// and if so, we'll just trim them and add ...
if (empty($finishline)) {
$final = $short_excerpt .'...';
} else {
$final = substr($short_excerpt, 0, $finishline+1);
}
return wpautop($final);
}
?>
// use this inside loop
// 220 is the character limit, you can change it to whatever value you need
<?php echo perfect_excerpt(220); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment