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
Let’s assume my menu structure is as follows, and I want to hide the Prestations menu item along with its child items:
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.
I hope this is helpful. Please feel free to reach out if you have any questions or need further clarification.
I think you can use https://wordpress.org/plugins/if-menu/ plugin and it will should do what you want without coding.
Thank You! 🙂