add custom class to wp_nav_menu using filter hook nav_menu_css_class

I have a custom post type in my wordpress theme. I want to add a custom class to the nav menu for the pages created in that custom post type. I read that you can use a filter hook: “nav_menu_css_class”, but my php chops are pretty limited. How do I set up that filter hook to apply only to my custom post type pages in the nav menu and give them a custom class?

Related posts

Leave a Reply

1 comment

  1. here is a simply example:

    add_filter('nav_menu_css_class', 'auto_custom_type_class', 10, 2 );
    function auto_custom_type_class($classes, $item) {
    
        if ($item->type_label == "CUSTOM_TYPE_NAME"){
            $classes[] = "New_Class";
        }
    
        return $classes;
    }
    

    just change CUSTOM_TYPE_NAME to the name of your custom post type and New_Class with the name of your class and paste this snippet in your theme’s functions.php file.