我的产品没有库存状态,只是库存数量。有没有办法让元查询将其值视为0或1?例如,首先是不是0的值,然后是0的值。
我现在的查询:
\'meta_query\' => array(
\'relation\' => \'AND\',
\'quantity_total\' => array(
\'key\' => \'total_quantity\',
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\',
),
\'price_lowest_first\' => array(
\'key\' => \'main_price\',
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\',
)
),
\'orderby\' => array(
\'quantity_total\' => \'DESC\',
\'price_lowest_first\' => \'ASC\'
)
EDIT:
现在,我使用了“库存”标志,下面是我的代码:
//sort by total quantity
if($sort !== \'4\'){
$args[\'meta_query\'][\'in_stock\'] = array(
\'key\' => \'1C_in_stock\',
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\'
);
$args[\'orderby\'] = array(
\'in_stock\' => \'DESC\'
);
}
//apply sort preferences to arguments
switch($sort){
#by stock status
case \'1\':
// \'1\' is default, do not want to move it to the default clause yet.
break;
#sort by price: lower first
case \'2\':
$args[\'meta_query\'][\'price_lowest_first\'] = array(
\'key\' => \'1C_price\'
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\'
);
$args[\'orderby\'][\'price_lowest_first\'] = \'ASC\';
break;
#sort by price:higher first
case \'3\':
$args[\'meta_query\'][\'price_highest_first\'] = array(
\'key\' => \'1C_price\',
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\',
);
$args[\'orderby\'][\'price_highest_first\'] = \'DESC\';
break;
#sort randomly
case \'4\':
$args[\'orderby\'] = \'rand\';
break;
}
但是否有按非零和零数量订购项目的查询?然后,按价格订购每组。
最合适的回答,由SO网友:Sally CJ 整理而成
如果我理解正确
可以使用CASE
语句,在ORDER BY
条款:
# group the quantity meta into two groups
CASE
# group one - all quantities that are 1 or more; we flag them as "1"
WHEN wp_postmeta.meta_value+0 > 0 THEN 1
# group two - all quantities that are 0 or less; we flag them as "2"
WHEN wp_postmeta.meta_value+0 <= 0 THEN 2
END ASC
在哪里
wp_postmeta.meta_value
是
total_quantity
元查询中的第一个元,以及
+0
意味着我们正在将元值转换为一个数字。
再加上CASE
对的声明ORDER BY
子句中,可以使用posts_orderby
hook. 下面是一个使用闭包和私有变量的示例:
// *Private variable used with the closure below.
$_do_filter = true;
add_filter( \'posts_orderby\',
function ( $orderby ) use ( &$_do_filter ) {
if ( $_do_filter ) {
$orderby = "CASE\\n" .
" WHEN wp_postmeta.meta_value+0 > 0 THEN 1\\n" .
" WHEN wp_postmeta.meta_value+0 <= 0 THEN 2\\n" .
"END ASC, $orderby";
}
return $orderby;
}
);
$query = new WP_Query( array(
\'meta_query\' => array(
\'relation\' => \'AND\',
\'quantity_total\' => array(
\'key\' => \'total_quantity\',
\'type\' => \'NUMERIC\',
\'compare\' => \'EXISTS\',
),
\'price_lowest_first\' => array(
\'key\' => \'main_price\',
\'type\' => \'DECIMAL(5, 2)\',
\'compare\' => \'EXISTS\',
),
),
\'orderby\' => array(
// we already have the CASE statement, so this is no longer needed
// \'quantity_total\' => \'DESC\',
\'price_lowest_first\' => \'ASC\',
),
// ... your other args.
) );
// Disable the filter.
$_do_filter = false;
// Then run your loop here..
// while ( $query->have_posts() ) ...
请注意
main_price
梅塔,我设置
type
到
DECIMAL(5, 2)
这样就可以根据小数点对价格进行排序。