首先,您希望使查询键可用,以便以后可以检查它们:
add_action( \'init\', \'custom_add_query_vars\' );
function custom_add_query_vars() {
add_query_var( \'location\' );
add_query_var( \'tag\' );
}
那么您要设置
tax_query
通过筛选WP查询:
add_filter( \'pre_get_posts\', \'custom_search_tax_query\' );
function custom_search_tax_query() {
// check this is a search query with post type of \'listings\'
if ( is_search() && get_query_var( \'post_type\')
&& ( get_query_var( \'post_type\' ) == \'listings\' ) ) {
// check for location query var
if ( get_query_var( \'location\' ) ) {
$location_query = array(
\'taxonomy\' => \'location\',
\'field\' => \'slug\',
\'terms\' => get_query_var( \'location\' ),
);
}
// check for tag query var
if ( get_query_var( \'tag\' ) ) {
$tag_query = array(
\'taxonomy\' => \'tag\',
\'field\' => \'slug\',
\'terms\' => get_query_var( \'tag\' ),
);
}
// create the tax_query array
if ( isset( $location_query ) && isset( $tag_query ) ) {
$tax_query = array( \'relation\' => \'AND\', $location_query, $tag_query );
} elseif ( isset( $location_query ) ) {$tax_query = array( $location_query );}
elseif ( isset( $tag_query ) ) {$tax_query = array( $tag_query );}
// finally set the tax_query
if ( isset( $tax_query ) ) {$query->set( \'tax_query\' => $tax_query );}
}
}
然后,您可以将搜索表单中的输入传递给键
location
和
tag
并获得您想要的回复帖子。:-)
备注:
无需返回$query
通过引用传递时从筛选器中删除尽管看起来很奇怪$tax_query
考虑到relation
参数-是否relation
是否设置小心tag
, 如果您实际使用的是标准标记分类法,则需要将其更改为post_tag
(标准标记的分类名称)中$tag_query
, 但在这里,我假设您添加了一个额外的分类法,实际上称为tag
.