I am conditionally showing menu items. All is fine but want to remove parent item if returning no child items.
For example if I have a parent menu (it will always be a custom link with #) called More and it has multiple child items (mostly one level). Now if I am hiding child items based on user roles and for some roles no child items available, in that case, I want to remove More menu items also since it has no child.
I am trying with the following code but since $item
is an object, array_search
won't work. So how can I check for child-parent and remove the menu item if it has no child?
array_search( $item[ 'ID' ], array_column( $item, 'menu_item_parent' ) )
Below is the working code that hides menu item based on user roles.
public static function exclude_menu_items( $items, $menu, $args ) {
if ( current_user_can( 'administrator' ) ) {
return $items;
}
foreach ( $items as $key => $item ) {
if ( $page = get_post( $item->object_id ) ) {
if ( $page->post_type == 'page' ) {
$template = get_post_meta( $page->ID, '_wp_page_template', TRUE );
$post_type = self::get_cpt_for_template( $template );
if ( $post_type && ( ! current_user_can( 'cp_access_' . $post_type ) || ! ( new self() )->is_current_user_granted_for_module( $post_type ) ) ) {
unset( $items[ $key ] );
}
}
}
}
return $items;
}