0

Wordpress let's users apply CSS classes to links under Appearances-->Menus.

Well based off of this, I would like to know if there is a way to hide links that have a certain CSS class. So say I apply the CSS class

.members

to one of my navigation links. The catch is, I would like this link to only show to users that are logged in.

I am a little stuck though as I don't know how to exactly go about doing this. Could something like:

if(is_user_logged_in()) {

}

I just don't know how I could target a CSS class.

0

You could use the body_class for this purpose, for example:

.members {
    display: none;
}
body.logged-in .members {
    display: block;
}
  • So no need to use PHP at all? Sounds promising. – Brian Oct 7 '13 at 15:55
  • as long as your theme is using the body_class function, otherwise adding the function is the only php involved. – Milo Oct 7 '13 at 15:57
  • I'll check to see if it is. If anything I'll add it. Thanks for the help. Really appreciate it. – Brian Oct 7 '13 at 16:00
  • I wouldn't do this. Since the PHP will still create the HTML elements, users could just undo the 'display:none' on any 'member-only' functionality. – AJ Zane Oct 7 '13 at 16:56
  • 1
    well obviously this is not a security measure. where ever those links go should be protected by a logged in check, which one can assume is the case – Milo Oct 7 '13 at 17:52
0

If you're comfortable with writing PHP code, you can get an array of each item in the menu by using wp_get_nav_menu_items(), and using the object's classes array to figure out which classes are applied to the item. Then you'll use is_user_logged_in() to display the link.

Something along the lines of:

    foreach ($items as $item){
        if ( in_array( 'members' , $item->classes ) ) {
            if ( is_user_logged_in() ) {
                echo '<a href="'.$menu_item->url.'">link</a>';
            }
        } else {
            echo '<a href="'.$menu_item->url.'">link</a>';
        }
    }

If you don't want to crack open and fiddle with some PHP, try playing with a permissions plugin such as http://wordpress.org/plugins/user-permissions/ or http://wordpress.org/plugins/members/ . I haven't personally tried to use one to set permissions on a menu, but these plugins will let you control permissions by user role on pretty much everything through the GUI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.