Here is the excerpt of the post on my home page. I want to end the excerpt with a sentence. In this case it is ‘ opportunities. ‘. I know how to modify the length but it won’t do what i want.
Here is excerpt from other website. Here you see excerpt ending with a proper sentence unlike the above which ends with the first word of next sentence ‘Proactively’.
After Implementing the solution by G.M. :-
This requires PHP 5.3+ (WP requires PHP 5.2.4+)
Edit
After @kaiser comment I try to run this on save/update to prevent page slow down on showing a lot of posts. This should be tested
Here is my version, keeping all html tags and also trimming the content after the last word in of a sentence
Just in case someone is using the answer, word of advice: This will ruin the Advanced Custom Fields. ACF also invokes
wp_insert_post_data
when creating or updating a field, but the$data
variable is not the same, and will result in the ACF field name to become some unreadable gibberish, which results in not being able to use the field.Here is a different solution, which uses WordPress in-built wp_trim_words() function to determine roughly how long the text should be, and then truncates the text at the end of that sentence (a little longer than the number of words specified).
Usage: echo im_trim_sentences($very_long_text, 90);
A custom “strpos_array()” function has also been included in this answer, because PHP’s strpos() function only accepts a string as the $needle, but we want to search for different sentence endings (full stop, or exclamation mark, etc).