Function get_queried_object() return NULL in custom taxonomy

You don’t need to use any query at all, especially not query_posts.

Instead, use the pre_get_posts action to make sure that any query for that taxonomy for a frontend archive, has the appropriate post types:


add_action( 'pre_get_posts', function( \WP_Query $q ) {
    // we only want the main query for galerie-kategorie archives
    if ( ! $q->is_main_query() || !$q->is_tax( 'galerie-kategorie' ) ) {
        return;
    }
    $q->set( 'post_type', 'galerie' );
});

Now it will make sure WP grabs what you wanted the first time around.

Otherwise, by using a whole new WP_Query/query_post you:

  • double the number of queries, WP did all that work and you’ve just thrown it in the trash and told it to do it all over again! Poor WP 🙁
  • Make your page twice as slow as it has to do everything twice
  • Breaks pagination! Now you have to do a tonne of extra work to get it working again, and you have to write custom pagination code to get the links working
  • Introduces compatibility problems with plugins and code that use pre_get_posts
  • Made your code longer
  • Cluttered up your templates, a pre_get_post filter can be hidden away in functions.php

If you ever need to modify ro change the posts WP fetches from the database, use pre_get_posts. Think of it like changing your food order before you give it to kitchen. The last thing you want is to order food, have it arrive, then change your mind and have to wait again for new food.