【问题标题】:Replace Woocommerce product variable price range from custom field values从自定义字段值替换 Woocommerce 产品可变价格范围
【发布时间】:2019-05-09 00:57:41
【问题描述】:

我想使用自定义字段为可变产品中的供应商添加价格。因此,我正在使用以下代码来获取可变产品自定义字段的最高和最低价格,但它什么也不返回。请帮助我找到如何从可变产品的自定义字段中获取价格。

    // Min and max variable prices
    add_filter( 'woocommerce_variable_sale_price_html', 'new_variable_price_format', 10, 2 );
    add_filter( 'woocommerce_variable_price_html', 'new_variable_price_format', 10, 2 );
    function new_variable_price_format( $price, $product ) {
    $price = get_post_meta( $product->get_id(), 'vendor_price_regu');
    echo "<pre>";
    print_r($price);
    echo "</pre>";
    return $price;
    }

【问题讨论】:

    标签: php wordpress woocommerce product price


    【解决方案1】:

    由于这是关于显示的可变价格范围,您需要获取所有变化价格并显示最小和最大自定义格式的价格以使其工作:

    add_filter( 'woocommerce_variable_price_html', 'custom_variable_price_html', 10, 2 );
    function custom_variable_price_html( $price, $product) {
        $prices = [];
        foreach($product->get_children() as $variation_id ){
            if( $vprice = get_post_meta( $variation_id, 'vendor_price_regu', true ) )
                $prices[] = $vprice;
        }
    
        if( sizeof($prices) > 0 ){
            sort($prices);
    
            $min_price = reset( $prices );
            $max_price = end( $prices );
    
            if ( $min_price == $max_price ) {
                 $price = wc_price($min_price);
            } else {
                $price = wc_price($min_price) . ' - ' . wc_price($max_price);
            }
        }
        return $price;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。它应该可以工作。

    【讨论】:

    • 非常感谢您的帮助。看起来不错。但它只返回最低价格。您能帮我获得最高和最低价格吗?
    • @Gurjit 抱歉,出了点小错误。再试一次。
    • 是的,它工作得很好。我有一个问题,我们可以使用 min() 和 max() 函数来代替 reset() 和 end() 吗?
    • @Gurjit 是的,你试试看……在我的代码中,我使用 Woocommerce 方式(他们使用 current() 和 end())……所以如果你使用 min() 和 max() 你不会需要排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2020-11-13
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多