
Adding Custom Classes into WordPress Menu
- June 10, 2016
- Leave a comment
Normally custom classes can be added into WP navigation menus from admin panel. But sometimes you need to add classes on conditional basis. In this scenario, you cannot add classes from WP admin panel.
For instance, in a project you are required to highlight the two menu items for two different users. You cannot do so from WordPress Dashboard.
In order to resolve this issue, the following code should be added in your Theme’s functions.php file:
1 2 3 4 5 6 7 8 9 10 11 |
function pt_custom_nav_classes( $classes, $item ){ $user_type = get_user_meta( get_current_user_id(), 'user_type', true ); if ( $user_type == 'student' && $item->title == 'Title' ) { $classes[] = 'highlight-menu-item'; } elseif ( $user_type == 'teacher' && $item->title == 'Title' ){ $classes[] = 'highlight-menu-item'; } return $classes; } add_filter('nav_menu_css_class' , 'pt_custom_nav_classes' , 10 , 2); |
This code will check the page title and user status (suppose – a student or teacher). If the set criteria match the mentioned condition, then highlight-menu-item class will be added. You can also check for other $item variables such as:
- $item->ID
- $item->title
- $item->slug
You can also display or hide navigation menu items on conditional basis after some modification in the above mentioned code.
User Comments