|

Fix wp_nav_menu on Custom Type Archives in WordPress

Recently I was working with an issue in WordPress where the site’s menu was not showing up on an archive page for one of my custom post types. There were a few troubleshooting things I tried, including the most common recommendation, use theme_location instead of menu when referencing the menu in your theme (code after the jump):

wp_nav_menu( array(
    'theme_location' => 'main-menu-slug',
) );

However, that wasn’t working. I did find another solution that got me part of the way there, which removed the taxonomy specifications if WordPress was building the menu.

function fix_nav_menu( $query ) {
    if ( $query->get( 'post_type' ) === 'nav_menu_item' ) {
    $query->set( 'tax_query', '' );
    }
}
add_action( 'pre_get_posts', 'fix_nav_menu' );

This didn’t completely work for me because I was using a meta_key to sort my posts, so I changed the if statement to reset a couple more query variables:

if ( $query->get( 'post_type' ) === 'nav_menu_item' ) {
    $query->set( 'tax_query', '' );
    $query->set( 'meta_key', '' );
    $query->set( 'orderby', '' );
}

That did the trick! It took me quite a bit of troubleshooting, so hopefully this will help you out if you’re trying to fix wp_nav_menu on Custom Post Type Archives.

One Comment

  1. It seems that this breaks the menu’s on all pages and anywhere the wp_nav_menu is called on the site since WP6.0.

    There is a bug in 6.0 that when this is in the functions.php file the WP menu adds every menu item and other wp nav menus to each wp nav on both the backend in the menu editor and the frontend of the site. Makes for a very large menu anywhere a wp menu is called.

    Example: https://accelerated.local/

Leave a Reply

Your email address will not be published. Required fields are marked *