admin管理员组

文章数量:1389392

I have one menu that I created called "Main Menu" and only want to show it to users that are logged in. I have only been able to find plugins that allow me to show/hide individual menu items, but not the entire menu. How can I do this?

I have one menu that I created called "Main Menu" and only want to show it to users that are logged in. I have only been able to find plugins that allow me to show/hide individual menu items, but not the entire menu. How can I do this?

Share Improve this question asked Apr 11, 2020 at 15:23 PeterPeter 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Assuming you have the ability to either edit the theme or child theme, in the file where the menu is called (probably header.php), use something like this:

<?php
    if( is_user_logged_in() ) :
        wp_nav_menu( array(
            'theme_location' => 'header-nav',
            'menu_id'        => 'header-menu',
        ) );
    endif;
?>

That'll be the preferred option because it won't load the navigation at all, so even someone savvy enough to look at the source code/developer console won't see it.

If you don't have the ability to edit the theme/child theme files, then you can do it using CSS:

#site-navigation {
    display:none;
}
body.logged-in #site-navigation{
    display:block;
}

A few notes, the CSS above addresses the <nav> tag for a site I've recently started building, you'll have to look at your source code/developer console and identify which element/container to add display:none; to. The important part is that WordPress adds the .logged-in class to the body tag, specifically to allow us to write different CSS/js rules/functions depending on users being logged in.

Like I said though, the CSS isn't the preferred option if what you're after is preventing users that aren't logged in from being able to locate items with a menu - for that, you'd want to use the conditional check at the top.

Addendum I should also add the you can add an else into the conditional statement and load a different menu, or a login link...

<?php
    if( is_user_logged_in() ) :
        wp_nav_menu( array(
            'theme_location' => 'header-nav',
            'menu_id'        => 'header-menu',
        ) );
    else :
        wp_nav_menu( array(
            'theme_location' => 'header-nav-notloggedin',
            'menu_id'        => 'header-menu-notloggedin',
        ) );
    endif;
?>

本文标签: navigationHide Menu Unless Logged In