Add custom taxonomy terms to WordPress menu dynamically & append #slug to url

If your menu is generated via wp_nav_menu, you can use a Custom Walker to add a dynamic submenu to a specific item.

First, the class, which would go in your theme’s functions.php file, or your own custom plugin:

class Walker_Author_Categories extends Walker_Nav_Menu {
    // we only need to override the function that closes each menu item,
    // this is where we can insert a submenu
    function end_el( &$output, $item, $depth=0, $args=array() ) {
        // if the current menu item being output is authors
        if( 'authors' == $item->title ){
            // get all of the author categories
            $author_cats = get_terms( array(
                'taxonomy' => 'author_categories',
                'hide_empty' => false,
            ) );
            if ( ! empty( $author_cats ) && ! is_wp_error( $author_cats ) ) {
                // url of the authors page
                // to be used to append #anchor links
                $parent_url = get_permalink( $item->object_id );
                // start a new list
                $output .= '<ul>';
                // iterate over each category
                // and add an li
                foreach( $author_cats as $author_cat ){
                    $slug = $author_cat->slug;
                    $name = $author_cat->name;
                    $format="<li><a href="%s#%s">%s</a></li>";
                    $output .= sprintf( $format, $parent_url, $slug, $name );
                }
                // close the list
                $output .= '</ul>';
            }
        }
        // close the parent li
        $output .= "</li>\n";  
    }
}

Then, where you output the menu, add the custom walker:

wp_nav_menu( array(
    'theme_location' => 'primary',
    'walker' => new Walker_Author_Categories
) );

Leave a Comment