Last active
January 30, 2018 16:21
-
-
Save morgyface/5d375795519f5ce66387ac2a980ae430 to your computer and use it in GitHub Desktop.
WordPress | Trim the excerpt
This file contains hidden or 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
| <?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 '…'; | |
| } | |
| } else { | |
| echo $excerpt_stripped; // The excerpt must be less than the char_limit so lets just print it. | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Overhauled in January 2018.