WP_Query 获取自定义分类下的帖子无效

WP_Query for getting posts under custom taxonomy not working

我正在尝试从自定义分类中获取自定义 post 类型。根据此处相关的文档和其他类似问题,我执行了以下操作:

$query = new WP_Query( array(
  'post_type' => 'job',
  'tax_query' => array(

     'taxonomy' => 'location',
     'field' => 'slug',
     'terms' => 'california'
   )
)

但问题是此查询正在获取所有 posts,而不仅仅是 "California" 分类法下的 posts。

如果需要更多信息,我可以提供更多代码编辑问题。

提前致谢!

在你的 while 循环中,记得切换

<?php

  while ( $query->have_posts() ) {
     $query->the_post();   
      // Important line, especially if you have
      //multiple WP_Query  invocations

     DO WHAT YOU WANT HERE

  wp_reset_postdata();
  }

 ?>

尝试这样的事情:

    $posts_array = get_posts(
        array(
            'posts_per_page' => -1,
            'post_type' => 'job',
            'tax_query' => array(
                array(
                    'taxonomy' => 'location',
                    'field' => 'slug',
                    'terms' => 'california',
          )
        )
    )
);

您缺少数组。 tax 查询参数可用于多个分类法。它接受一个数组数组。

Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays). This construct allows you to query multiple taxonomies by using the relation parameter in the first (outer) array to describe the boolean relationship between the taxonomy arrays.

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

改变这个:

'tax_query' => array(

     'taxonomy' => 'location',
     'field' => 'slug',
     'terms' => 'california'
   )

为此:

'tax_query' => array(
    array(
        'taxonomy' => 'location',
        'field'    => 'slug',
        'terms'    => 'california',
    ),
),