Skip to content

Instantly share code, notes, and snippets.

@jaredatch
Created October 22, 2013 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredatch/7093295 to your computer and use it in GitHub Desktop.
Save jaredatch/7093295 to your computer and use it in GitHub Desktop.
Dynamically populate a submenu with posts
<?php
/**
* Adds the most recent "Some Category" posts as sub menu items under
* the "Some Category Parent" parent menu item.
*
* @param array $items
* @param array $menu
* @param array $args
* @return array
*/
function ja_dynamic_submenu( $items, $menu, $args ) {
// Only proceed if we are looking at the correct menu and not in the admin
if ( $menu->slug != 'primary-navigation' || is_admin() )
return $items;
// Placeholders
$new_menu_items = array();
$menu_id = '';
// Find the menu item we are looking for, with the title "Some Category Parent"
foreach ( $items as $item ) {
if ( 'Some Category Parent' == $item->title )
$menu_id = $item->ID;
}
// Create the query for the posts to list
$menu_args = array (
'posts_per_page' => 4,
'category_name' => 'some-category',
);
$menu = new WP_Query( $menu_args ); while( $menu->have_posts() ) : $menu->the_post();
$new_menu_items[] = array(
'title' => get_the_title(),
'url' => get_permalink(),
);
endwhile;
$menu_order = count( $items ) + 1;
// Add the new menu items
if ( !empty( $new_menu_items ) && !empty( $menu_id ) ) {
foreach ( $new_menu_items as $new_menu_item ) {
$new_item = new stdClass;
$new_item->menu_item_parent = $menu_id;
$new_item->url = $new_menu_item['url'];
$new_item->title = $new_menu_item['title'];
$new_item->menu_order = $menu_order;
$items[] = $new_item;
$menu_order++;
}
}
wp_reset_postdata();
wp_reset_query();
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'ja_dynamic_submenu', 10, 3 );
@moyarich
Copy link

moyarich commented Feb 4, 2015

$new_item = new stdClass;

caused the following errors for me.

Notice: Undefined property: stdClass::$object_id in C:\Apache\htdocs\wordpress\wp-includes\nav-menu-template.php on line 518

Notice: Undefined property: stdClass::$db_id in C:\Apache\htdocs\wordpress\wp-includes\nav-menu-template.php on line 626

To fix the problem, i replaced the code on line 44 with:

$_post = new stdClass;
$new_item = new WP_Post($_post);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment