I have a menu:
Activities
Projects
About Us
News
(not counting submenu items).
Now “Activities” has no submenu.
I created custom content type “project”.
My boss want to fill the menu “Activities” with the list of all projects automatically.
Can it be done without rewriting anew all WP menu output code?
Yes! Yes it can, you will need to hook into the filter used by the walker, e.g.:
add_filter( 'walker_nav_menu_start_el', 'menu_show_project_post', 10, 4 );
function menu_show_project_post( $item_output="", $item = '', $depth="", $args="" ) {
global $post;
if ( is_array( $item->classes ) ) {
$query = false;
foreach( $item->classes as $class ) {
if ( $class == 'project_posts') {
$query = true;
break;
}
}
if ( $query ) {
$the_posts = get_posts( array(
'post_type' => 'project',
'numberposts' => 5
) );
if ( ! empty( $the_posts ) ) {
$new_html[] = '<ul class="sub-menu">';
foreach( ( array ) $the_posts as $post ) {
setup_postdata( $post );
$new_html[] = '<li class="menu-item">';
$new_html[] = '<a href="' . get_permalink( ) . '" class="depth-' . ( $depth ? $depth + 1 : 2 ) . '">';
$new_html[] = the_title('','',false );
$new_html[] = '</a>';
$new_html[] = '</li>';
}
wp_reset_postdata();
$new_html[] = '</ul>';
$item_output .= implode( "\n", $new_html );
}
}
}
return $item_output;
}
With this code in functions.php, any menu item containing the class ‘project_posts’ will be given a submenu containing 5 posts of type project.
Modify the code as you wish to show however many posts or post types as you want