What about checking the ID value of each menu item like the following:
if( $item->ID === 45): // ADD THIS MENU-ITEM ID CHECK
// Query the lasts ten category posts
$category_ten_last_posts = array(
'posts_per_page' => 11,
'category_name' => 'mamba',
'orderby' => 'date',
'order' => 'DESC'
);
$posts = get_posts( $category_ten_last_posts );
foreach ( $posts as $post ) {
//...
}
endif;
ps: I moved the get_posts()
out of the foreach input argument.
Update
This works on my install:
!is_admin() AND add_filter( 'wp_get_nav_menu_items', 'display_lasts_ten_posts_for_categories_menu_item', 10, 3 );
// Add the ten last posts of af categroy menu item in a sub menu
function display_lasts_ten_posts_for_categories_menu_item( $items, $menu, $args ){
$menu_order = count($items);
$child_items = array();
foreach ( $items as $item ):
if( $item->ID === 45 ):
// Query the lasts ten category posts
$category_ten_last_posts = array(
'posts_per_page' => 11,
'category_name' => 'mamba',
'orderby' => 'date',
'order' => 'DESC'
);
$posts = get_posts( $category_ten_last_posts );
foreach( $posts as $post ):
// Add sub menu item
$post->menu_item_parent = $item->ID;
$post->post_type="nav_menu_item";
$post->object="custom";
$post->type="custom";
$post->menu_order = ++ $menu_order;
$post->title = $post->post_title;
$post->url = get_permalink( $post->ID );
/* add children */
$child_items[] = $post;
endforeach;
endif;
endforeach;
return array_merge( $items, $child_items );
}