使用 WooCommerce wc

互联网 更新时间:2023-04-26 21:03:25

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

本文发布于:2023-04-26 21:03:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/hyzx/aac9105b11ec9897128e2f8aede2e56b.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:WooCommerce   wc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 89741文章数
  • 23110阅读数
  • 0评论数