我已经为“课程”的自定义帖子类型创建了一个新查询。然后使用tax\\u query过滤这些结果,查询3个与1个或多个术语ID匹配的自定义分类法。这些分类法是从搜索页面传递的。
以下是迄今为止正在运行的代码:
// Lets emulate the posted ID\'s from the course search widget
// with some static term ID\'s for each custom taxonomy.
$search_course_area = array(65, 62);
$search_course_level = array(117); //52 for further filtering
$search_course_mode = array(54, 56);
//Begin a new query
$query = new WP_Query(
array(
//Retreive ALL course posts
\'post_type\' => \'course\',
\'posts_per_page\' => \'-1\',
//Filter taxonomies by id\'s passed from course finder widget
\'tax_query\' => array(
//Set the relation condition for the filters in
//this case we\'re using AND as it is explicity set
//by the user when searching
\'relation\' => \'AND\',
//First check retreive course-area\'s based on ID
array(
\'taxonomy\' => \'course-area\',
\'field\' => \'id\',
\'terms\' => $search_course_area
),
//And again for the second taxonomy
array(
\'taxonomy\' => \'study-levels\',
\'field\' => \'id\',
\'terms\' => $search_course_level
),
//Finally check retreive course-level\'s based on ID
array(
\'taxonomy\' => \'course-mode\',
\'field\' => \'id\',
\'terms\' => $search_course_mode
),
)
)
);
我有点纠结的是,如果传递的数组是空的,这显然会破坏查询,并且不会返回任何结果。
解决这个问题最干净的方法是什么?我可以这样做:
if (isset($search_course_area)) {
echo "array(
\'taxonomy\' => \'course-area\',
\'field\' => \'id\',
\'terms\' => $search_course_area
),";
};
但我觉得这不是最好的方法?
非常感谢您的时间和任何帮助,我真的很感激!
最合适的回答,由SO网友:jessica 整理而成
您可以在WP_Query
实例化:
<?php
$tax_query = array(\'relation\' => \'AND\');
if (isset($search_course_area))
{
$tax_query[] = array(
\'taxonomy\' => \'course-area\',
\'field\' => \'id\',
\'terms\' => $search_course_area
);
}
if (isset($search_course_level))
{
$tax_query[] = array(
\'taxonomy\' => \'study-levels\',
\'field\' => \'id\',
\'terms\' => $search_course_level
);
}
if (isset($search_course_mode))
{
$tax_query[] = array(
\'taxonomy\' => \'course-mode\',
\'field\' => \'id\',
\'terms\' => $search_course_mode
);
}
$query = new WP_Query(
array(
//Retreive ALL course posts
\'post_type\' => \'course\',
\'posts_per_page\' => \'-1\',
//Filter taxonomies by id\'s passed from course finder widget
\'tax_query\' => $tax_query,
)
);
?>
SO网友:Wesley Andrade
以防万一,如果现在有人看到这一点,如果查询实例中有多个case,那么应该用另一个数组包装变量。。类似于:
$meta_query = array();
if ( 0 == $current_user->ID ) {
$meta_query[] = array(array(
\'key\' => \'restrito_para_visualizar\',
\'value\' => \'1\',
\'compare\' => \'!=\',
\'type\' => \'CHAR\',
),
array(
\'key\' => \'ativo\',
\'value\' => \'1\',
\'compare\' => \'=\',
\'type\' => \'NUMERIC\',
));
} else {
$meta_query[] = array(
array(
\'key\' => \'ativo\',
\'value\' => \'1\',
\'compare\' => \'=\',
\'type\' => \'NUMERIC\',
));
}