How to add multiple custom excerpt length in wordpress

In archive pages, we use the_excerpt() function to show excerpt of each posts. Be default, wordpress uses 55 words as excerpt if you don’t enter anything in Excerpt meta field. Now, if you want to change the length of excerpt, there is a filter available for that. excerpt_length is the filter that you can use to customize the excerpt length, just use it following way:

[php]

function new_excerpt_length($length) {
return 20;
}
add_filter(‘excerpt_length’, ‘new_excerpt_length’);
[/php]

You can change 20 to some other integer.

But what if you need to use multiple length of excerpt in different archive pages? We, in that case I prefer to use a custom excerpt function. That will give the output exactly same as the_excerpt() function. Just, you need to call a custom function that we will write now and pass the length as a parameter. Here is the function:

[php]
function custom_excerpt($charlength = 55) {
$res = ‘

‘;
$excerpt = get_the_excerpt();
$charlength++;
if(strlen($excerpt) > $charlength) {
$subex = substr($excerpt, 0, $charlength-5);
$exwords = explode(” “, $subex);
$excut = -(strlen($exwords[count($exwords) – 1]));
if($excut < 0) {
$res .= substr($subex, 0, $excut);
} else {
$res .= $subex;
}
$res .= "[…]";
} else {
$res .= $excerpt;
}
$res .= '

‘;
echo $res;
}
[/php]

What you have to do is to call custom_excerpt() function with a length like custom_excerpt(40). In my function, if you don’t pass any parameter then the default value is set to 55. You can change with your own.

You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name ‘mu-plugins’. If there is no folder in that name, then create a folder, name it ‘mu-plugins’, create a file inside that, give any name you like and paste the code in there. You don’t need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code.

Make sure you use the function within a loop.

Leave a Reply

%d bloggers like this: