I know I can control the length of excerpts using a filter, however it sets the length globally. In my case I have different lengths of excerpts on three different pages.
This is what I have now. I’d like to improve it so it doesn’t truncate words.
$content_to_excerpt = strip_tags( strip_shortcodes( get_the_content() ) );
$pos = strpos($content_to_excerpt, ' ', 160);
if ($pos !== false) {
echo "<p>" . substr($content_to_excerpt, 0, $pos) . "...</p>";
}
Set the filter dynamically based on the page you are loading. If category archive pages have a 100 word excerpt, but posts have a 10 word excerpt, and everything else uses the default:
You can get even more specific, giving specific categories a different length.
In response to Rarst, a new template function
the_excerpt_length()
for outputting the excerpt with a specific number of words:This would be used in your template file, i.e.:
I know I’ve seen this question on StackOverflow before. Not specific to WordPress excerpt, but on truncating strings on PHP without truncate words. Looking back on StackOverflow itself, I found this link pretty helpful on this subject.
The code being used there is:
Hope this helps!