In my WP custom menu, one item has a dropdown list below it that lists all instances of some CPT.

The only way I know to do that is by creating the list somewhere else in the DOM with PHP and then moving that list right inside the custom menu item with Javascript.

Problem: this requires Javascript.

Is there a way to do the same thing by "hacking" the function that builds the custom menu so that, when the menu gets created by PHP, it already incorporates this lists of CPT instances?


What you want can be done. It's just not likely to be really clean and neat.

You can accomplish this by using a custom Walker Class for the wp_nav_menu() when you insert it.

class My_Walker_Class extends Walker_Nav_Menu {

    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $output .= sprintf( "\n<li><a href='%s'%s>%s</a></li>\n",
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',

         * Here you will need to add a conditional to see if the parent menu item was found
         * and if so go into a subroutine that grabs your CPT list. Add it all to $output.

        if ( $item->object_id == 111 ) // Match by ID
            // Call external function that generates CPT list
            $output .= my_get_cpt_list();


$args = array(
    'theme_location'  => 'my_theme_location',
    'menu'            => 'my_menu',
    'container'       => 'div',
    'container_class' => '',
    'container_id'    => '',
    'menu_class'      => 'menu',
    'menu_id'         => '',
    'echo'            => true,
    'fallback_cb'     => 'wp_page_menu',
    'before'          => '',
    'after'           => '',
    'link_before'     => '',
    'link_after'      => '',
    'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
    'depth'           => 0,
    'walker'          => new My_Walker_Class()

wp_nav_menu( $args );

Of course adjust as needed to make it actually work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.