This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Questions, comments, or suggestion for improvement? Leave a comment on the GitHub Gist page.