Why nav_menu_css_class doesn’t work with apply_filters?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x