Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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->url,
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',
            $item->title
        );

        /**
         * 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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