Created
December 7, 2016 17:32
-
-
Save WPDevHQ/05c9ec05fc42c248f1297738869295dc to your computer and use it in GitHub Desktop.
Perfect Excerpts for WordPress
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
// 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); | |
} | |
?> |
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
// 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