Custom Post Types posts as submenus in Nav Menu

Here’s an example on modifying a menu element to add things. In this example, a category item is extended to have a dynamically generated sub menu listing posts, where the menu item has a class of showposts-X where X is the number of posts to show:

function menu_show_category_posts( $item_output="", $item = '', $depth="", $args="" ) {
    global $post;

    $item_output = icit_add_class_attrib( $item_output, 'depth-' . ( $depth ? $depth : 1 ) );

    if ( $item->type == 'taxonomy' && $item->object == 'category' && is_array( $item->classes ) ) {
        $query = false;
        $showposts = 10;
        $preview = 0;
        $new_html = array( );
        $i = 0;

        foreach( $item->classes as $class ) {
            if ( preg_match( '/^showposts-?(\d*)/', $class, $matches ) ) {
                $query = true;
                $showposts = ! empty( $matches[ 1 ] ) && intval( $matches[ 1 ] ) ? intval( $matches[ 1 ] ) : 10;
            }
        }

        if ( $query ) {
            $the_posts = get_posts( array(
                             'category' => $item->object_id,
                             'numberposts' => $showposts
                            ) );

            if ( ! empty( $the_posts ) ) {
                $new_html[] = '<ul class="sub-menu">';

                foreach( ( array ) $the_posts as $post ) {
                    setup_postdata( $post );
                    $new_html[] = '<li class="">';
                    $new_html[] = the_title( '<a href="' . get_permalink( ) . '" class="depth-' . ( $depth ? $depth + 1 : 2 ) . '">', '</a>', false );
                    $new_html[] = '</li>';
                }

                $new_html[] = '</ul>';
                $item_output .= implode( "\n", $new_html );
            }
        }
    }

    return $item_output;
}

add_filter( 'walker_nav_menu_start_el', 'menu_show_media_post', 10, 4 );

Leave a Comment