John Davidson

php - Wordpress Meta Query Relation with Multiple Arguments

0 comments
Message:


I am looking for a solution by which I can apply 'OR' relation depending upon the meta key,
In the below code you can see that 'relation' =>'AND' is applied which makes AND clause for every meta key like asset_category , asset_type .
If the post has true value for both asset_category and asset type then only post will be found in query.


What I want is different relation for different meta keys, for example:
Meta key active_inactive should be always true,
Meta key asset_category is optional so AND clause needs to apply on it


Can someone help me to make the code?
Any help appreciated.


$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);


My Answer:
'OR' is applied to all meta queries. However, I want to apply 'OR' relation only for specific meta keys. Here is an example code:

php
$args = array(
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'blue',
'compare' => '='
),
array(
'relation' => 'OR',
array(
'key' => 'size',
'value' => 'small',
'compare' => '='
),
array(
'key' => 'material',
'value' => 'wood',
'compare' => '='
)
)
)
);

$query = new WP_Query( $args );


In the above code, I want to apply 'OR' relation only for the 'size' and 'material' meta keys, while keeping 'AND' relation for the 'color' meta key. This can be achieved by nesting the meta queries and specifying the 'relation' key for each nested query.

This way, you can have different relation types for different meta keys in your meta query.

Rate this post

3 of 5 based on 7528 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us