The nav_menu_items_{$post_type_name} WordPress PHP filter modifies the posts displayed in the ‘View All’ tab of the current post type’s menu items meta box.
Usage
add_filter( 'nav_menu_items_post', 'your_custom_function', 10, 3 ); function your_custom_function( $posts, $args, $post_type ) { // your custom code here return $posts; }
Parameters
- $posts (object[]): The posts for the current post type. Mostly WP_Post objects, but can also contain “fake” post objects to represent other menu items.
- $args (array): An array of WP_Query arguments.
- $post_type (WP_Post_Type): The current post type object for this menu item meta box.
More information
See WordPress Developer Resources: nav_menu_items_{$post_type_name}
Examples
Exclude private posts from menu items
Exclude private posts from the ‘View All’ tab in the post menu items meta box.
add_filter( 'nav_menu_items_post', 'exclude_private_posts', 10, 3 ); function exclude_private_posts( $posts, $args, $post_type ) { return array_filter( $posts, function( $post ) { return $post->post_status !== 'private'; }); }
Add custom post type to menu items
Include a custom post type called ‘portfolio’ in the ‘View All’ tab of the post menu items meta box.
add_filter( 'nav_menu_items_post', 'add_portfolio_to_menu_items', 10, 3 ); function add_portfolio_to_menu_items( $posts, $args, $post_type ) { if ( $post_type->name === 'post' ) { $portfolio_posts = get_posts( array( 'post_type' => 'portfolio' ) ); $posts = array_merge( $posts, $portfolio_posts ); } return $posts; }
Limit menu items to specific categories
Show only posts from categories ‘news’ and ‘events’ in the ‘View All’ tab of the post menu items meta box.
add_filter( 'nav_menu_items_post', 'limit_categories_in_menu_items', 10, 3 ); function limit_categories_in_menu_items( $posts, $args, $post_type ) { $allowed_categories = array( 'news', 'events' ); return array_filter( $posts, function( $post ) use ( $allowed_categories ) { $post_categories = wp_get_post_categories( $post->ID, array( 'fields' => 'slugs' ) ); return count( array_intersect( $post_categories, $allowed_categories ) ) > 0; }); }
Sort menu items by title
Sort posts alphabetically by their titles in the ‘View All’ tab of the post menu items meta box.
add_filter( 'nav_menu_items_post', 'sort_posts_by_title', 10, 3 ); function sort_posts_by_title( $posts, $args, $post_type ) { usort( $posts, function( $a, $b ) { return strcmp( $a->post_title, $b->post_title ); }); return $posts; }