我正在寻找一个解决方案,我可以根据元键应用'OR'关系,在下面的代码中,您可以看到应用了'relation' =>'AND'
,它为每个元键(如asset_category
,asset_type
)创建AND子句。如果post对于asset_category和asset type都是true,那么在query中只会找到post。
我想要的是不同的元键不同的关系,例如:元键active_inactive
应该总是为真,元键asset_category
是可选的,所以需要在它上面应用AND子句
有人能帮我写代码吗?谢谢你的帮助。
$args = array(
'post_type' => 'asset',
's' => $keyword,
'posts_per_page' => -1,
'orderby'=> 'title' ,
'order' => 'ASC',
'post_status' =>'publish',
'meta_query' => array(
'relation' =>'AND',
array(
'key' => 'active_inactive',
'value' => 'Active',
'compare' => '=',
),
)
);
if(isset($_GET['category'])){
if(is_array($_GET['category'])){
foreach($_GET['category'] as $cat){
$args['meta_query'][]=array(
'key' => 'asset_category',
'value' => $cat,
'compare' => 'LIKE',
),
);
}
}else{
$args['meta_query'][]=array(
'key' => 'asset_category',
'value' => $_GET['category'],
'compare' => 'LIKE',
);
}
}
if(isset($_GET['assetType'])){
if(is_array($_GET['assetType'])){
foreach($_GET['assetType'] as $cat){
$args['meta_query'][]=array(
'key' => 'asset_type',
'value' => $cat,
'compare' => 'LIKE',
);
}
}else{
$args['meta_query'][]=array(
'key' => 'asset_type',
'value' => $_GET['asset_type'],
'compare' => 'LIKE',
);
}
}
if(isset($_GET['levels'])){
$args['meta_query'][]=array(
'key' => 'difficulty_level',
'value' => $_GET['levels'],
'compare' => 'IN',
);
}
$wp_query_arr[] = new WP_Query($args);
$filter[] = array(
'key' => 'active_inactive',
'value' => 'Active',
'compare' => '=',
);
if(isset($_GET['category'])){
if(is_array($_GET['category'])){
foreach($_GET['category'] as $cat){
$filter[]=array(
'key' => 'asset_category',
'value' => $cat,
'compare' => 'LIKE',
),
);
}
}else{
$filter[]=array(
'key' => 'asset_category',
'value' => $_GET['category'],
'compare' => 'LIKE',
);
}
}
if(isset($_GET['assetType'])){
if(is_array($_GET['assetType'])){
foreach($_GET['assetType'] as $cat){
$filter[]=array(
'key' => 'asset_type',
'value' => $cat,
'compare' => 'LIKE',
);
}
}else{
$filter[]=array(
'key' => 'asset_type',
'value' => $_GET['asset_type'],
'compare' => 'LIKE',
);
}
}
if(isset($_GET['levels'])){
$filter[]=array(
'key' => 'difficulty_level',
'value' => $_GET['levels'],
'compare' => 'IN',
);
}
if(count($filter) > 1 ){
$args = array(
'post_type' => 'asset',
's' => $keyword,
'posts_per_page' => -1,
'orderby'=> 'title' ,
'order' => 'ASC',
'post_status' =>'publish',
'meta_query' => array(
'relation' =>'AND',
$filter,
)
);
} else {
$args = array(
'post_type' => 'asset',
's' => $keyword,
'posts_per_page' => -1,
'orderby'=> 'title' ,
'order' => 'ASC',
'post_status' =>'publish',
'meta_query' => array(
$filter
)
);
}
$wp_query_arr[] = new WP_Query($args);