skip to Main Content

I have a membership website, and I would like to show a menu item (and its sub-links) only to logged-in users in WordPress.

I’m using the code below, but it only hides the parent link and does not include the child sub-links (they are still visible, and I would like to hide them).

add_filter('wp_nav_menu_objects', 'hide_menu_conditional', 10, 2);
function hide_menu_conditional($items, $args) {
        // Check if the USer is logged in
        foreach($items as $key => $item) {
            if(is_user_logged_in()) {
                if($item->title == 'Members Area') {
                    unset($items[$key]);
                    break;
                }
            }
        }
    return $items;
}

What can I do to hide the parent link and its children?

Thank you

2

Answers


  1. Let’s assume my menu structure is as follows, and I want to hide the Prestations menu item along with its child items:

    - Prestations
      - Logout
      - Sample Page
    - Product
    - Contact
    

    First, run var_dump($item) before the if() statement to identify the ID of the parent menu item (Prestations). In my case, the ID is "54".

    Add $item->menu_item_parent === "54" in the if statement with an or operator, so the statement will be true for the parent menu and for all it’s
    children, all of them will be removed by the unset function.

    Get the parent ID

    function hide_menu_conditional($items, $args){
        foreach ($items as $key => $item) {
    
            // echo "<pre>";
            // var_dump($item);
            // echo "</pre>";
    
            // Check if the User is logged in
            if (is_user_logged_in()) {
                if ( $item->title == 'Prestations' || $item->menu_item_parent === "54" ) {
                    unset($items[$key]);
                }
            }
            
        }
        return $items;
    }
    

    This is my answer for the Question: What can I do to hide the parent
    link and its children?

    I hope this is helpful. Please feel free to reach out if you have any questions or need further clarification.

    Login or Signup to reply.
  2. I think you can use https://wordpress.org/plugins/if-menu/ plugin and it will should do what you want without coding.

    Thank You! 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search