How do I apply a class to custom menu items based on user roles

I have a members section on my site and they see specific custom menu items. I’m seeking a way to simply apply a star to the <li> based on it’s permission level and what the user’s role is.

Something to the effect of.

Read More
if( current_user_can('integrator') || current_user_can('distributor')) :

This is what I have so far and it applies a class to every menu item if the user’s role is (whatever). I essentially need to apply the class if another class is present and the user’s role is (whatever)…

add_filter('nav_menu_css_class' , 'my_nav_special_class' , 10 , 2);
function my_nav_special_class($classes, $item){
        if (current_user_can('integrator') || current_user_can('distributor')){
            $classes[] = 'PARTNER_STAR';
        }
    return $classes;
}

Courtesy Bainternet from this post

Any ideas would be appreciated

Update: I also want to note that I’m using “Role Scoper” to handle permissions. They do have a template function is_restricted_rs() but I’m honestly unsure how to use it currently.

Related posts

Leave a Reply

3 comments

  1. WRT to your question “need to apply the class if another class is present and the user’s role is (whatever)”

    The easiest was to do this, isn’t in the code, but yet in the CSS. You can target an element that has more then once class. So, using your class PARTNER_STAR and if your other class is say another you can have your css such that

    .another { /* targets all elements with another set */ }
    .PARTNER_STAR { /* targets all elements with PARTNER_STAR set */ }
    .another.PARTNER_STAR { /* targets elements that have BOTH PARTNER_STAR and another set */ }
    

    Tying in the idea of @robertwbradford you can just set one parent element, and don’t need it on every single one. If you have multiple roles, that just need one style, you can still have your if statement, just apply the css to a high-level parent element.

    .PARTNER_STAR .another { /* targets all elements with another inside PARTNER_STAR */ }
    
  2. Instead of adding the classes directly to the li elements, you could add it to a wrapper. Or why not the body tag so it’s available for multiple elements? Something like:

    # functions.php
    function user_role_class() {
      // Some code here to return a string containing the user's role(s).
      // Perhaps see http://codex.wordpress.org/Function_Reference/get_role as a start?
    }
    
    # header.php
    ...
    <body <?php body_class(user_role_class()); ?>>
    ...
    

    Then in your stylesheet something like this:

    # style.css
    ul.menu{/*default menu formatting here*/}
    body.integrator ul.menu{/*role-specific menu formatting here*/}
    

    This type of styling is powerful in that it can really reduce the amount of classes required throughout your code.