Woocommerce显示默认的变化价格

时间:2015-08-31 20:55:11

标签: wordpress woocommerce variations

我正在使用Woocommerce和产品变体,我的所有变体都定义了默认变体。我想知道,我如何找到默认变体并显示它的价格。

这是我到目前为止所获得的代码,但它显示了最便宜的变化价格,而我正在寻找我的默认变体产品价格。

// Use WC 2.0 variable price format, now include sale price strikeout
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
    $price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;

}

我在这里找到了代码示例Woocommerce variation product price to show default

2 个答案:

答案 0 :(得分:5)

我没有找到这个问题的答案(如何显示默认产品差异而非价格范围的价格?)所以我创建了代码:

add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);

    function custom_variation_price( $price, $product ) {

        foreach($product->get_available_variations() as $pav){
            $def=true;
            foreach($product->get_variation_default_attributes() as $defkey=>$defval){
                if($pav['attributes']['attribute_'.$defkey]!=$defval){
                    $def=false;             
                }   
            }
            if($def){
                $price = $pav['display_price'];         
            }
        }   

        return woocommerce_price($price);

    }

此插件显示默认变体的价格,当然如果您之前设置了默认值。测试了woocommerce版本2.6.2。

答案 1 :(得分:0)

这是我自己的解决方案,认为它可能更好,但我不是一个php开发人员,所以随意添加改进。

FirstOrDefault()