Shorten Category Names in WordPress Dropdown Menus

An interesting problem was raised on the WordPress support forums recently: Is there any way to shorten category names in dropdown menus so they don’t scroll off the side of the screen?

Here’s an example of what I mean. Suppose you have a movie blog where you are using movie titles as categories. You want to put a dropdown menu in the sidebar using the Categories widget, so your readers can easily browse to any particular movie that interests them. It all sounds good in theory, except that some movies have really long titles that make the dropdown list too wide to fit into the sidebar:

A WordPress category dropdown menu with long category names

That doesn’t look very good, does it? What you really need is a way to automatically truncate those long titles down to some reasonable length. Fortunately, I found an easy way to do it. All you need to do is put this code into your functions.php file:

function truncate_list_cats($cat) {
$limit = 25; // do not make this less than 15
if(strlen($cat) > $limit)
$cat = substr($cat, 0, $limit) . '...';
return $cat;
}
add_filter('list_cats', 'truncate_list_cats');

After adding the above code, the category titles in the dropdown menu are truncated to a maximum length of 25 characters (or whatever number you set as the ‘limit’):

A WordPress category dropdown menu with truncated category names

One small caveat I should mention: this filter affects the output of both wp_list_categories and wp_dropdown_categories (there is no way to make it affect only one or the other), so if your theme uses a category list somewhere other than the sidebar, the category names will be truncated there, too.

Addendum

If you’d prefer to shorten the category names to the nearest whole word, rather than cutting off part of a word, see my related article Truncate Long Titles to the Nearest Whole Word Using PHP strrpos. You can use the method I describe there in line 4 of the above code.

More From the Blog

Comments

  1. katzw says:

    Thank you so much! This made my morning :)

Comments are closed.