questions

WordPress Nav Menu not displaying on custom archive page

Rate this post

I am currently creating a WordPress theme and stumbled across an issue I don’t fully understand. I display my nav menu on the position mega_menu, using:

wp_nav_menu(array('theme_location' => 'mega_menu'));

And this works on all normal posts and pages. However, when I am on the archive page of my custom post type menschen the menu does not show up. var_dumping the nav menu on the position of mega_menu does return a WP_Term object, but getting the items returns an empty array. I don’t understand this strange behaviour and hope somebody can help me.

I try to display the menu in the header.php file and call get_header() on the archive page as well.

Here’s the registration of my custom post type:

function thg_custom_post_type()
{
    register_post_type(
        'menschen',
         array(
            'labels'      => array(
                'name'          => __('Menschen'),
                'singular_name' => __('Mensch'),
            ),
            'public'            => true,
            'has_archive'       => true,
            'show_in_rest'      => true,
            'taxonomies'        => array( 'category' ),
            'menu_icon'         => 'dashicons-businesswoman',
            'supports'          => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
            'rewrite'           => array( 'slug' => 'menschen' ),
        )
    );
}

add_action('init', 'thg_custom_post_type');

 

✔️Solution:

After searching the forums for this question, I’ve noticed that some people also have this bug when changing the sorting order of queries by using the pre_get_posts WP hook. If you change the order for all post types (that includes menu items) your menu items might not appear properly as they are posts themselves.

This can be solved by including an if statement checking if the current query is the main query. For example, if you have this function:

// Change sort order of archive page to alphabetical
add_action( 'pre_get_posts', 'my_change_sort_order');
    function my_change_sort_order($query){
        if (is_archive() && is_post_type_archive( 'menschen' )):
           //Set the order ASC or DESC
           $query->set( 'order', 'ASC' );
           //Set the orderby
           $query->set( 'meta_key', 'nachname' );
           $query->set( 'orderby', 'meta_value' );
           $query->set( 'posts_per_page', -1 );
        endif;
    };

You would have to add && $query->is_main_query() to the if statement. This means that the function is ignored for all queries but the main one, so menu items don’t disappear.

Leave a Reply

Your email address will not be published.

Back to top button