Last updated on September 13, 2023

Remove Pages from Menu

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Remove pages from a menu.

To remove specific pages from a WordPress menu, you can use the wp_nav_menu_objects filter to modify the menu items before they are rendered. This allows you to exclude specific pages from being displayed in the menu. Here’s an example of how you can achieve this:

function wpsnippets_exclude_pages_from_menu( $items, $menu, $args ) {
    // Array of page IDs to exclude from the menu
    $exclude_pages = array( 2, 5, 8 );

    // Initialize empty array
    $filtered_items = array();

    // Loop over all menu items
    foreach ( $items as $item ) {

        // Skip menu items if their page's ID is in the $exclude_pages array
        if ( in_array( $item->object_id, $exclude_pages ) ) {
            continue;
        }

        // Add item to the $filtered_items array
        $filtered_items[] = $item;
    }

    // Return the $filtered_items only
    return $filtered_items;
}

add_filter( 'wp_nav_menu_objects', 'wpsnippets_exclude_pages_from_menu', 10, 3 );

In this example, $exclude_pages is an array of page IDs that you want to exclude from the menu. Replace the page IDs with the actual IDs of the pages you want to remove from the menu.

Inside the wpsnippets_exclude_pages_from_menu() function, a loop iterates through each menu item. If the object_id of the item matches any of the IDs in the $exclude_pages array, the item is skipped and not added to the $filtered_items array. This effectively removes the specified pages from the menu.

By adding this code snippet to your site, you can remove the specified pages from the WordPress menu when it is rendered. The menu items for the excluded pages will not be displayed.

Last updated on September 13, 2023. Originally posted on May 19, 2023.

Leave a Reply