How to set count for the_excerpt function in symbols?

We are know, for create excerpt of posts in WordPress, used function the_excerpt. This function, by default output first 55 words of content (post). Ok, but how make, if we need set limit quantity text not words, but symbols? For example, we need output first 120 symbols of the post, how make it? On the Internet, you can find many variants, but all of them don’t satisfy me, so how suggest work in loop or need of edit template/theme, but is not always practical and aesthetics of the code is lost 🙂 The answer, that I propose enough simple and concise, it contain only 4 lines of the code, that need put in your functions.php file.

How to trim the_excerpt to a certain character count

In addition, I think it would be good, if I will write here more some functions, that override default works for the_excerpt and that used, practical on each projects: change quantity words for the_excerpt, remove dots (...) on the end of excerpt, add link on the post, on the end of excerpt:

/* Excerpt Length Is 120 Symbols */
add_filter('the_excerpt', 'trim_excerpt');
function trim_excerpt($excerpt) {
	return mb_substr($excerpt, 0, 122);//this parametr must be need quantity symbols + 2, check it
}
/* Change Excerpt Length */
function new_excerpt_length($length) {
	return 20; //excerpt length is 20 words
}
add_filter('excerpt_length', 'new_excerpt_length');
/* Remove '...' On The End Of Excerpt */
add_filter('excerpt_more', function($more) {
	return '...';
});
/* Add Link On The Post On The End Of Excerpt */
add_filter('excerpt_more', 'new_excerpt_more');
function new_excerpt_more($more) {
	global $post;
	return '<a href="'. get_permalink($post->ID) . '">Read more...</a>';
}

Sources:

  1. https://wpquestions.com/How_do_I_trim_the_excerpt_to_a_certain_character_count/716
  2. https://wp-kama.ru/function/the_excerpt

Leave Comment

Your email address will not be published. Required fields are marked *