Using WordPress ‘customize_nav_menu_available_items’ PHP filter

The customize_nav_menu_available_items WordPress PHP filter allows you to modify the available menu items in a WordPress navigation menu.

Usage

add_filter('customize_nav_menu_available_items', 'your_custom_function', 10, 4);

function your_custom_function($items, $object_type, $object_name, $page) {
    // your custom code here
    return $items;
}

Parameters

  • $items (array) – The array of menu items.
  • $object_type (string) – The object type.
  • $object_name (string) – The object name.
  • $page (int) – The current page number.

More information

See WordPress Developer Resources: customize_nav_menu_available_items

Examples

Add a custom menu item

Add a custom menu item to the available menu items.

add_filter('customize_nav_menu_available_items', 'add_custom_menu_item', 10, 4);

function add_custom_menu_item($items, $object_type, $object_name, $page) {
    $custom_item = array(
        'title' => 'Custom Item',
        'url' => 'https://example.com/custom-item',
        'type' => 'custom',
    );
    $items[] = (object) $custom_item;
    return $items;
}

Remove all posts from available menu items

Remove all posts from the available menu items.

add_filter('customize_nav_menu_available_items', 'remove_posts_from_menu_items', 10, 4);

function remove_posts_from_menu_items($items, $object_type, $object_name, $page) {
    return array_filter($items, function($item) {
        return $item->type !== 'post_type' || $item->object !== 'post';
    });
}

Filter menu items by title

Filter available menu items by title containing the word “Featured”.

add_filter('customize_nav_menu_available_items', 'filter_menu_items_by_title', 10, 4);

function filter_menu_items_by_title($items, $object_type, $object_name, $page) {
    return array_filter($items, function($item) {
        return strpos($item->title, 'Featured') !== false;
    });
}

Sort menu items alphabetically

Sort available menu items alphabetically by title.

add_filter('customize_nav_menu_available_items', 'sort_menu_items_alphabetically', 10, 4);

function sort_menu_items_alphabetically($items, $object_type, $object_name, $page) {
    usort($items, function($a, $b) {
        return strcmp($a->title, $b->title);
    });
    return $items;
}

Limit the number of available menu items

Limit the number of available menu items to 10.

add_filter('customize_nav_menu_available_items', 'limit_available_menu_items', 10, 4);

function limit_available_menu_items($items, $object_type, $object_name, $page) {
    return array_slice($items, 0, 10);
}