Using WordPress ‘is_nav_menu_item()’ PHP function

The is_nav_menu_item() WordPress PHP function determines whether the given ID is a nav menu item.

Usage

is_nav_menu_item($menu_item_id);

Example:

// Check if the ID 42 is a nav menu item
$is_nav_menu_item = is_nav_menu_item(42);
echo $is_nav_menu_item; // Returns true if it is, false otherwise

Parameters

  • $menu_item_id int (Required) – The ID of the potential nav menu item.

More information

See WordPress Developer Resources: is_nav_menu_item()

Examples

Check if a post is a nav menu item

In this example, we will check if a specific post is a nav menu item.

$post_id = 42;
if (is_nav_menu_item($post_id)) {
    echo "Post ID $post_id is a nav menu item.";
} else {
    echo "Post ID $post_id is not a nav menu item.";
}

Check multiple IDs for nav menu items

In this example, we will loop through an array of IDs to check if they are nav menu items.

$ids = array(10, 20, 30, 40, 50);

foreach ($ids as $id) {
    if (is_nav_menu_item($id)) {
        echo "ID $id is a nav menu item.<br />";
    } else {
        echo "ID $id is not a nav menu item.<br />";
    }
}

Check all menu items in a menu

In this example, we will check all items in a specific menu to see if they are nav menu items.

$menu_name = 'main-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);

foreach ($menu_items as $menu_item) {
    if (is_nav_menu_item($menu_item->ID)) {
        echo "Menu item with ID {$menu_item->ID} is a nav menu item.<br />";
    }
}

Remove non-nav menu items from an array

In this example, we will remove non-nav menu items from an array of IDs.

$ids = array(10, 20, 30, 40, 50);
$nav_menu_items = array();

foreach ($ids as $id) {
    if (is_nav_menu_item($id)) {
        $nav_menu_items[] = $id;
    }
}

print_r($nav_menu_items); // Array with only nav menu item IDs

Display nav menu items with a custom message

In this example, we will display a custom message for nav menu items.

$ids = array(10, 20, 30, 40, 50);

foreach ($ids as $id) {
    if (is_nav_menu_item($id)) {
        echo "ID $id is a nav menu item with a custom message.<br />";
    } else {
        echo "ID $id is not a nav menu item.<br />";
    }
}