我很难让tax\\u query充当帖子的过滤器。我想要的是,它将显示有县和状态条款的cpt,但如果没有为状态或县提供条款,它也可以工作。因此,让帖子显示县分类法中是否有“亚当斯”县的术语,以及状态分类法中是否有“锁定”的术语。但如果不提供一个县,它也需要发挥作用,只有一个地位,反之亦然。
这是我的代码:
<?php
$args = array(
\'post_type\' => \'property\',
\'posts_per_page\' => 5000,
\'tax_query\' => array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'Status\',
\'field\' => \'slug\',
\'terms\' => explode( \',\', $st_term_final_string )
),
array(
\'taxonomy\' => \'County\',
\'field\' => \'slug\',
\'terms\' => explode( \',\', $il_term_final_string )
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo \'<div class="entry-content">\';
echo get_the_post_thumbnail();
the_content();
echo \'</div>\';
endwhile;
?>
有什么提示可以帮我找到正确的方向吗?
提前感谢
最合适的回答,由SO网友:gmazzap 整理而成
使用以下内容更改代码:
$args = array(
\'post_type\' => \'property\',
\'posts_per_page\' => 5000,
);
$statuses = explode( \',\', $st_term_final_string);
$terms = explode( \',\', $il_term_final_string );
if ( $statuses || $terms ) {
$args[\'tax_query\'] = array();
if ( $statuses ) {
$args[\'tax_query\'][] = array(
\'taxonomy\' => \'Status\',
\'field\' => \'slug\',
\'terms\' => $statuses
);
}
if ( $terms ) {
$args[\'tax_query\'][] = array(
\'taxonomy\' => \'County\',
\'field\' => \'slug\',
\'terms\' => $terms
);
}
if ( $statuses && $terms ) $args[\'tax_query\'][\'relation\'] = \'AND\';
$loop = new WP_Query( $args );
// do your stuff here
} else {
// You have no statuses nor county, I don\'t know what you want to do in this case
}
希望有帮助。