Get all posts from custom taxonomy in Wordpress

后端 未结 4 566
广开言路
广开言路 2020-12-25 09:51

Is there a way to get all the posts from a taxonomy in Wordpress ?

In taxonomy.php, I have this code that gets the posts from the term related to the cu

4条回答
  •  隐瞒了意图╮
    2020-12-25 10:25

    Unlike for post types, WordPress does not have a route for the taxonomy slug itself.

    To make the taxonomy slug itself list all posts that have any term of the taxonomy assigned, you need to use the EXISTS operator of tax_query in WP_Query:

    // Register a taxonomy 'location' with slug '/location'.
    register_taxonomy('location', ['post'], [
      'labels' => [
        'name' => _x('Locations', 'taxonomy', 'mydomain'),
        'singular_name' => _x('Location', 'taxonomy', 'mydomain'),
        'add_new_item' => _x('Add New Location', 'taxonomy', 'mydomain'),
      ],
      'public' => TRUE,
      'query_var' => TRUE,
      'rewrite' => [
        'slug' => 'location',
      ],
    ]);
    
    // Register the path '/location' as a known route.
    add_rewrite_rule('^location/?$', 'index.php?taxonomy=location', 'top');
    
    // Use the EXISTS operator to find all posts that are
    // associated with any term of the taxonomy.
    add_action('pre_get_posts', 'pre_get_posts');
    function pre_get_posts(\WP_Query $query) {
      if (is_admin()) {
        return;
      }
      if ($query->is_main_query() && $query->query === ['taxonomy' => 'location']) {
        $query->set('tax_query', [
          [   
            'taxonomy' => 'location',
            'operator' => 'EXISTS',
          ],  
        ]);
        // Announce this custom route as a taxonomy listing page
        // to the theme layer.
        $query->is_front_page = FALSE;
        $query->is_home = FALSE;
        $query->is_tax = TRUE;
        $query->is_archive = TRUE;
      }
    }
    

提交回复
热议问题