我正在Wordpress中构建一个网格,该网格具有将用作过滤器的自定义分类术语。我一直在使用'terms' => array()
中的变量。一种类型的变量起作用,一种不起作用。
以下是查询:
$args = array(
'posts_per_page' => -1,
'post_type' => 'plant',
'orderby' => 'name',
'order' => 'ASC',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'trail_location',
'field' => 'slug',
'terms' => array($trailLocationList),
),
array(
'taxonomy' => 'bloom_time',
'field' => 'slug',
'terms' => array($bloomTime),
)
)
);
$loop = new WP_Query( $args );
我可以将查询字符串值转换为var并且它可以工作:
$bloomTime = $_GET['bloom_time'];
'terms' => array($bloomTime).
静态值有效:'terms' => array('loc1', 'loc2', 'loc3')
。
什么不起作用是从现有分类标本的数组创建变量。
$terms = get_terms("trail_location");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
$trailLocationList[] = $term->slug;
}
}
$trailLocationList = implode("', '",$trailLocationList);
$trailLocationList = "'".$trailLocationList."'";
var在静态示例('loc1', 'loc2', 'loc3')
中输出我需要的确切字符串,但由于某种原因查询不起作用。我测试过,两个变量都是字符串。
答案 0 :(得分:1)
根据我的评论,其中带逗号的字符串不是数组。 删除implode步骤并使用$ trailLocationList数组作为术语:
$terms = get_terms("trail_location");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
$trailLocationList[] = $term->slug;
}
}
/* why?? dont do this
$trailLocationList = implode("', '",$trailLocationList);
$trailLocationList = "'".$trailLocationList."'";
*/
$args = array(
'posts_per_page' => -1,
'post_type' => 'plant',
'orderby' => 'name',
'order' => 'ASC',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'trail_location',
'field' => 'slug',
//'terms' => array($trailLocationList), wrong
'terms' => $trailLocationList //correct
),
array(
'taxonomy' => 'bloom_time',
'field' => 'slug',
'terms' => array($bloomTime),
)
)
);
$loop = new WP_Query( $args );