Question

I was trying to add css class to nav items.

The documented function call in WordPress docs was

apply_filters( 'nav_menu_css_class', string[] $classes, WP_Post $item, stdClass $args, int $depth )

But I tried adding the following to functions.php in my child theme doesn't work.

apply_filters('nav_menu_css_class', ['nav-item']);

But the adding the following to functions.php works as expected.

add_filter('nav_menu_css_class', fn () => ['nav-item']);

Why do add_filter works but not apply_filters?

Was it helpful?

Solution

Because that's not what apply_filters() does. You'll even see the usage guide and examples at your link all use add_filter(). Also see the official docs on Filters.

Using apply_filters() makes a value filterable. add_filter() is used to filter a filterable value by passing a function that does the filtering.

WordPress uses apply_filters('nav_menu_css_class', ..., which allows you to use add_filter() to modify its value. So if you want to modify the nav menu CSS classes, you need to add a filter, with add_filter().

The reason apply_filters() is shown in the docs you linked is because it's showing how that filter was originally defined. Not how to use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top