Skip to content

Instantly share code, notes, and snippets.

@adamrosloniec
Created November 15, 2019 04:15
Show Gist options
  • Save adamrosloniec/d606d68f652151242307005ae0cb44cf to your computer and use it in GitHub Desktop.
Save adamrosloniec/d606d68f652151242307005ae0cb44cf to your computer and use it in GitHub Desktop.
WordPress - The best way to get_the_excerpt with character limit
// Source: https://stackoverflow.com/a/10173268
function get_the_excerpt_with_characters_limit($text, $length) {
// Don't cut if too short
if (strlen($text) < $length + 10) {
return $text;
}
// Find next space after desired length
$break_pos = strpos($text, ' ', $length);
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . " …";
}
// example usage:
echo get_the_excerpt_with_characters_limit(get_the_excerpt(get_the_id()), 160);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment