Loi*_*tec 6
可变产品是按价格过滤的复杂东西......所以以下内容并不完美,但向您展示了一种启用价格范围的方法WC_Product_Query
。
因此,以下函数将启用自定义价格范围WC_Product_Query
查询:
add_filter( 'woomerce_product_data_store_cpt_get_products_query', 'handle_price_range_query_var', 10, 2 );
function handle_price_range_query_var( $query, $query_vars ) {
if ( ! empty( $query_vars['price_range'] ) ) {
$price_range = explode( '|', esc_attr($query_vars['price_range']) );
if ( is_array($price_range) && count($price_range) == 2 ) {
$query['meta_query']['relation'] = 'AND';
$query['meta_query'][] = array(
'key' => '_price',
'value' => reset($price_range), // From price value
'pare' => '>=',
'type' => 'NUMERIC'
);
$query['meta_query'][] = array(
'key' => '_price',
'value' => end($price_range), // To price value
'pare' => '<=',
'type' => 'NUMERIC'
);
$query['orderby'] = 'meta_value_num'; // sort by price
$query['order'] = 'ASC'; // In ascending order
}
}
return $query;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
示例用法
处理浮点数。 第一个价格与第二个价格由管道隔开|
这里我们查询 10.25 美元到 50 美元(价格范围)的产品:
$products = wc_get_products( [
'limit' => 20,
'status' => 'publish',
'price_range' => '10.25|50', // The first price is separated from the 2nd one with a pipe
] );
echo '<ul>';
foreach( $products as $product ) {
echo '<li><a href="'.$product->get_permalink().'">'.$product->get_name().' '.$product->get_price_html().'</a></li>';
}
echo '</ul>';
要仅过滤变量 products,您可以将以下行添加到查询中:
'type' => 'variable',
文档: wc_get_products 和 WC_Product_Query
更多推荐
WooCommerce,wc
发布评论