Limit the manual excerpt in WordPress
Recently I was working on a project where I needed to use the wordpress post/page manual excerpt and truncate it. I figured this would be easy, so tried using the following from the codex…
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
Once I’d put this in my functions.php file I reloaded the site and what did I see…
Nothing, it didn’t truncate the text, why didn’t it work?
Well after some googling I found out that you can only truncate the auto generated excerpt which is created when you call ‘the_excerpt()’.
I really needed this functionality, so I created this simple snippet you can put in your functions file to truncate the manual excerpt or anything you can echo (just incase).
In this example I’ve added the excerpt to my pages post type, but you can easily do this to regular posts too.
First just add this to your functions.php
// This add the excerpt widget to your pages in the admin area
add_action( 'init', 'add_excerpts_to_pages' );
function add_excerpts_to_pages() {
add_post_type_support( 'page', 'excerpt' );
}
// This creates the function for truncating
// $string = the echoed text you’d like to truncate i.e. the_excerpt()
function limit_excerpt($string, $word_limit) {
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(' ', $words);
}
Then just add this to your page.php
// this displays the excerpts first 15 words and then an ellipses
echo limit_excerpt($excerpt,15) . "…\r\n";
Pretty simple, but really handy, You can also use this to truncate the_content() too, just replace $excerpt with $content.
Let me know what you think, and if you have any ideas for improvements in the comments.
2 Comments
Add a CommentUseful information shared..I am very pleased to study this article..Many thanks for giving us nice information…Website Template
I’ve been trying to get this thing to work for a while, seems obvious now. I don’t know why this isn’t a normal feature of the manual excerpt… seems bizarre!