wp_get_nav_menu_items( int|string|WP_Term $menu, array $args = array() ): array|false
Retrieves all menu items of a navigation menu.
Contents
Description
Note: Most arguments passed to the $args
parameter – save for ‘output_key’ – are specifically for retrieving nav_menu_item posts from get_posts() and may only indirectly affect the ultimate ordering and content of the resulting nav menu items that get returned from this function.
Parameters
-
$menu
int|string|WP_Term Required -
Menu ID, slug, name, or object.
-
$args
array Optional -
Arguments to pass to get_posts() .
order
stringHow to order nav menu items as queried with get_posts() .
Will be ignored if'output'
is ARRAY_A. Default'ASC'
.orderby
stringField to order menu items by as retrieved from get_posts() .
Supply an orderby field via'output_key'
to affect the output order of nav menu items. Default'menu_order'
.post_type
stringMenu items post type. Default'nav_menu_item'
.post_status
stringMenu items post status. Default'publish'
.output
stringHow to order outputted menu items. Default ARRAY_A.output_key
stringKey to use for ordering the actual menu items that get returned. Note that that is not a get_posts() argument and will only affect output of menu items processed in this function. Default'menu_order'
.nopaging
boolWhether to retrieve all menu items (true) or paginate (false). Default true.update_menu_item_cache
boolWhether to update the menu item cache. Default true.
More Arguments from get_posts( ... $args )
Array or string of Query parameters.
attachment_id
intAttachment post ID. Used for'attachment'
post_type.author
int|stringAuthor ID, or comma-separated list of IDs.author_name
stringUser'user_nicename'
.author__in
int[]An array of author IDs to query from.author__not_in
int[]An array of author IDs not to query from.cache_results
boolWhether to cache post information. Default true.cat
int|stringCategory ID or comma-separated list of IDs (this or any children).category__and
int[]An array of category IDs (AND in).category__in
int[]An array of category IDs (OR in, no children).category__not_in
int[]An array of category IDs (NOT in).category_name
stringUse category slug (not name, this or any children).comment_count
array|intFilter results by comment count. Provide an integer to match comment count exactly. Provide an array with integer'value'
and'compare'
operator ('='
,'!='
,'>'
,'>='
,'<'
,'<='
) to compare against comment_count in a specific way.comment_status
stringComment status.comments_per_page
intThe number of comments to return per page.
Default'comments_per_page'
option.date_query
arrayday
intDay of the month. Accepts numbers 1-31.exact
boolWhether to search by exact keyword. Default false.fields
stringPost fields to query for. Accepts:
''
Returns an array of complete post objects (WP_Post[]
).'ids'
Returns an array of post IDs (int[]
).'id=>parent'
Returns an associative array of parent post IDs, keyed by post ID (int[]
).
''
.hour
intHour of the day. Accepts numbers 0-23.ignore_sticky_posts
int|boolWhether to ignore sticky posts or not. Setting this to false excludes stickies from'post__in'
. Accepts1|true
,0|false
.
Default false.m
intCombination YearMonth. Accepts any four-digit year and month numbers 01-12.meta_key
string|string[]Meta key or keys to filter by.meta_value
string|string[]Meta value or values to filter by.meta_compare
stringMySQL operator used for comparing the meta value.
See WP_Meta_Query::__construct() for accepted values and default value.meta_compare_key
stringMySQL operator used for comparing the meta key.
See WP_Meta_Query::__construct() for accepted values and default value.meta_type
stringMySQL data type that the meta_value column will be CAST to for comparisons.
See WP_Meta_Query::__construct() for accepted values and default value.meta_type_key
stringMySQL data type that the meta_key column will be CAST to for comparisons.
See WP_Meta_Query::__construct() for accepted values and default value.meta_query
arrayAn associative array of WP_Meta_Query arguments.
See WP_Meta_Query::__construct() for accepted values.menu_order
intThe menu order of the posts.minute
intMinute of the hour. Accepts numbers 0-59.monthnum
intThe two-digit month. Accepts numbers 1-12.name
stringPost slug.nopaging
boolShow all posts (true) or paginate (false). Default false.no_found_rows
boolWhether to skip counting the total rows found. Enabling can improve performance. Default false.offset
intThe number of posts to offset before retrieval.order
stringDesignates ascending or descending order of posts. Default'DESC'
.
Accepts'ASC'
,'DESC'
.orderby
string|arraySort retrieved posts by parameter. One or more options may be passed.
To use'meta_value'
, or'meta_value_num'
,'meta_key=keyname'
must be also be defined. To sort by a specific$meta_query
clause, use that clause's array key. Accepts:
'none'
'name'
'author'
'date'
'title'
'modified'
'menu_order'
'parent'
'ID'
'rand'
'relevance'
'RAND(x)'
(where'x'
is an integer seed value)'comment_count'
'meta_value'
'meta_value_num'
'post__in'
'post_name__in'
'post_parent__in'
- The array keys of
$meta_query
.
'date'
, except when a search is being performed, when the default is'relevance'
.p
intPost ID.page
intShow the number of posts that would show up on page X of a static front page.paged
intThe number of the current page.page_id
intPage ID.pagename
stringPage slug.perm
stringShow posts if user has the appropriate capability.ping_status
stringPing status.post__in
int[]An array of post IDs to retrieve, sticky posts will be included.post__not_in
int[]An array of post IDs not to retrieve. Note: a string of comma- separated IDs will NOT work.post_mime_type
stringThe mime type of the post. Used for'attachment'
post_type.post_name__in
string[]An array of post slugs that results must match.post_parent
intPage ID to retrieve child pages for. Use 0 to only retrieve top-level pages.post_parent__in
int[]An array containing parent page IDs to query child pages from.post_parent__not_in
int[]An array containing parent page IDs not to query child pages from.post_type
string|string[]A post type slug (string) or array of post type slugs.
Default'any'
if using'tax_query'
.post_status
string|string[]A post status (string) or array of post statuses.posts_per_page
intThe number of posts to query for. Use -1 to request all posts.posts_per_archive_page
intThe number of posts to query for by archive page. Overrides'posts_per_page'
when is_archive() , or is_search() are true.s
stringSearch keyword(s). Prepending a term with a hyphen will exclude posts matching that term. Eg, 'pillow -sofa' will return posts containing'pillow'
but not'sofa'
. The character used for exclusion can be modified using the the'wp_query_search_exclusion_prefix'
filter.search_columns
string[]Array of column names to be searched. Accepts'post_title'
,'post_excerpt'
and'post_content'
. Default empty array.second
intSecond of the minute. Accepts numbers 0-59.sentence
boolWhether to search by phrase. Default false.suppress_filters
boolWhether to suppress filters. Default false.tag
stringTag slug. Comma-separated (either), Plus-separated (all).tag__and
int[]An array of tag IDs (AND in).tag__in
int[]An array of tag IDs (OR in).tag__not_in
int[]An array of tag IDs (NOT in).tag_id
intTag id or comma-separated list of IDs.tag_slug__and
string[]An array of tag slugs (AND in).tag_slug__in
string[]An array of tag slugs (OR in). unless'ignore_sticky_posts'
is true. Note: a string of comma-separated IDs will NOT work.tax_query
arraytitle
stringPost title.update_post_meta_cache
boolWhether to update the post meta cache. Default true.update_post_term_cache
boolWhether to update the post term cache. Default true.update_menu_item_cache
boolWhether to update the menu item cache. Default false.lazy_load_term_meta
boolWhether to lazy-load term meta. Setting to false will disable cache priming for term meta, so that each get_term_meta() call will hit the database.
Defaults to the value of$update_post_term_cache
.w
intThe week number of the year. Accepts numbers 0-53.year
intThe four-digit year. Accepts any four-digit year.
Default:
array()
Return
array|false Array of menu items, otherwise false.
Source
File: wp-includes/nav-menu.php
.
View all references
function wp_get_nav_menu_items( $menu, $args = array() ) {
$menu = wp_get_nav_menu_object( $menu );
if ( ! $menu ) {
return false;
}
if ( ! taxonomy_exists( 'nav_menu' ) ) {
return false;
}
$defaults = array(
'order' => 'ASC',
'orderby' => 'menu_order',
'post_type' => 'nav_menu_item',
'post_status' => 'publish',
'output' => ARRAY_A,
'output_key' => 'menu_order',
'nopaging' => true,
'update_menu_item_cache' => true,
'tax_query' => array(
array(
'taxonomy' => 'nav_menu',
'field' => 'term_taxonomy_id',
'terms' => $menu->term_taxonomy_id,
),
),
);
$args = wp_parse_args( $args, $defaults );
if ( $menu->count > 0 ) {
$items = get_posts( $args );
} else {
$items = array();
}
$items = array_map( 'wp_setup_nav_menu_item', $items );
if ( ! is_admin() ) { // Remove invalid items only on front end.
$items = array_filter( $items, '_is_valid_nav_menu_item' );
}
if ( ARRAY_A === $args['output'] ) {
$items = wp_list_sort(
$items,
array(
$args['output_key'] => 'ASC',
)
);
$i = 1;
foreach ( $items as $k => $item ) {
$items[ $k ]->{$args['output_key']} = $i++;
}
}
/**
* Filters the navigation menu items being returned.
*
* @since 3.0.0
*
* @param array $items An array of menu item post objects.
* @param object $menu The menu object.
* @param array $args An array of arguments used to retrieve menu item objects.
*/
return apply_filters( 'wp_get_nav_menu_items', $items, $menu, $args );
}
Hooks
-
apply_filters( 'wp_get_nav_menu_items',
array $items ,object $menu ,array $args ) -
Filters the navigation menu items being returned.
Changelog
Version | Description |
---|---|
3.0.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Building bootstrap 3 menu with submenu items without use WP_nav_walker (boostrap)! (Require bootstrap.css and bootstrap.js)
Building menu list with children (submenus) and selecting the menu by it’s location:
Get simple array of menu.
Top ↑
Feedback
A simplified and more ‘JSON Friendly’ take:
— By charlyripp —
modified to get nested menu
function wp_get_nested_menu_array($current_menu) { $array_menu = wp_get_nav_menu_items($current_menu); $menu = array(); foreach ($array_menu as $m) { if (empty($m->menu_item_parent)) { $menu[$m->ID] = array(); $menu[$m->ID]['ID'] = $m->ID; $menu[$m->ID]['title'] = $m->title; $menu[$m->ID]['url'] = $m->url; $menu[$m->ID]['children'] = array(); } } $submenu = array(); foreach ($array_menu as $m) { if ($m->menu_item_parent) { $submenu[$m->ID] = array(); $submenu[$m->ID]['ID'] = $m->ID; $submenu[$m->ID]['title'] = $m->title; $submenu[$m->ID]['url'] = $m->url; $submenu[$m->ID]['parent'] = $m->menu_item_parent; if (isset($submenu[$m->menu_item_parent])) { $submenu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID]; $mainparentid = $submenu[$m->menu_item_parent]['parent']; $menu[$mainparentid]['children'][$m->menu_item_parent] = $submenu[$m->menu_item_parent]; }else{ $menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID]; } } } return $menu; }
— By kelvincys —Building simple menu list
Create a shortcode that takes a menu ID and prints a simple list of links. Add this to your functions.php file.
Shortcode syntax: [my_custom_navigation menu_id=123]
I have tested this menu , it supports sub menu , submenu will have arrow , also current page parent and menu item will have active class.
Here are two functions that can be used to add the menu to the REST API and retrieve individual menu items:
This allows us to access both:
https://example.com/wp-json/custom/menu
andhttps://example.com/wp-json/custom/menu/{menuID}
If you’re having issues with this function returning empty arrays since version 6.0 (as i did) make sure you’re not accidentally adjusting the
$query
, for example by setting thepost_type
to a custom type in apre_get_posts
action.Build 3 level hierarchical menu
Here’s a simple recursive solution to get an array of a menu and all submenus: