How to Change the Relation to 'AND' for the 'in_stock' Condition in WordPress Query
To change the relation to 'AND' for the 'in_stock' condition, you can modify the code as follows:
$idarray=array();
$data = array(
'post_type' => 'qqproduct',
'post_status' => 'publish',
'orderby' => 'DATE',
'order' => 'DESC',
'posts_per_page' => $per_page,
'paged' => $paged,
);
$meta_query = array(); // Initialize the meta_query array outside the loop
foreach ( $results as $key => $value ) {
if($key == 'qcat') {
if($value){
if($value != 'all' ){
$cat_query=array('relation' => 'OR',);
$catos = (explode(',', $value));
foreach ( $catos as $cato) {
$cat_query[] = [
'taxonomy' => 'qqcpat',
'field' => 'term_id',
'terms' => $cato,
];
$keys[] = $cato;
}
$data['tax_query']=array(array($cat_query),);
}
}
} elseif($key == 'offset') {
} elseif($key == 'in_stock') {
$meta_query[] = array(
'key' => 'qqp_qty',
'value' => array('0'),
'compare' => '>'
);
$keys[] = 'in_stock';
} elseif ($key == 'sortby') {
if ($value == 'newest') {
$data['orderby'] = 'DATE';
} elseif ($value == 'discount') {
$meta_query[] = array(
'key' => 'qqpd_price',
'value' => '',
'compare' => 'NOT IN'
);
} elseif ($value == 'review') {
$meta_query[] = array(
'key' => 'qq_product_rate',
'value' => '',
'compare' => 'NOT IN'
);
$data['orderby'] = 'meta_value_num';
} elseif ($value == 'topsale') {
$meta_query[] = array(
'key' => 'qq_total_views',
'value' => '',
'compare' => 'NOT IN'
);
$data['orderby'] = 'meta_value_num';
}
$keys[] = $value;
} else {
if ($value) {
$stros = explode(',', $value);
$trainer_query = array('relation' => 'OR');
foreach ($stros as $stro) {
$trainer_query[] = [
'key' => 'qq_att_' . $key,
'value' => $stro,
'compare' => 'LIKE',
];
$keys[] = $stro;
}
$meta_query[] = $trainer_query;
}
}
}
if (!empty($meta_query)) {
$meta_query['relation'] = 'OR'; // Add the relation when meta_query is not empty
$data['meta_query'] = $meta_query;
}
// Change the relation to 'AND' for the 'in_stock' condition
if (in_array('in_stock', $keys)) {
$in_stock_query = array(
'relation' => 'AND',
$meta_query,
);
$data['meta_query'] = $in_stock_query;
}
This code checks if the 'in_stock' condition is included in the query, and if so, creates a new meta_query array with the 'AND' relation and includes the existing meta_query array inside it.
原文地址: https://www.cveoy.top/t/topic/qefK 著作权归作者所有。请勿转载和采集!