Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active January 30, 2018 16:21
Show Gist options
  • Select an option

  • Save morgyface/5d375795519f5ce66387ac2a980ae430 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/5d375795519f5ce66387ac2a980ae430 to your computer and use it in GitHub Desktop.
WordPress | Trim the excerpt
<?php
$excerpt = get_the_excerpt();
$char_limit = 110;
$excerpt_stripped = strip_tags( $excerpt ); // Remove any tags using the strip_tags function.
$excerpt_length = strlen( $excerpt_stripped ); // Now lets count the characters so we can compare
if ( $excerpt_length > $char_limit ) { // Now work out if we need to trim the character length.
$offset = $char_limit - $excerpt_length; // This gives us a negative value.
$position = strrpos( $excerpt_stripped, ' ', $offset ); // This starts looking for a space backwards from the offset
$trimmed_excerpt = substr( $excerpt_stripped, 0, $position ); // Trim up until the point of the last space.
$last_character = substr( $trimmed_excerpt, -1 ); // Identify the last character of the newly trimmed excerpt
echo $trimmed_excerpt;
if ( $last_character != '.' ) {
// If the string ends with a full-stop we don't want to add an ellipsis
echo '&hellip;';
}
} else {
echo $excerpt_stripped; // The excerpt must be less than the char_limit so lets just print it.
}
?>
@morgyface
Copy link
Copy Markdown
Author

Overhauled in January 2018.

@morgyface
Copy link
Copy Markdown
Author

There's also a function version right here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment