显示 Woocommerce 可变产品中后缀的选定变体价格

Display selected variation price suffixed in Woocommerce variable products

我正在使用这个功能,所以我得到了默认的变化价格,但我想在价格后显示我的价格后缀:

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);
}

我现在输出的是例如“€15,00”,但我希望它显示的是“€15,00 每公斤”,'per kilo' 是价格后缀

您的代码已过时,因为 Woocommerce 3 (get_variation_default_attributes() woocommerce_price() 是已弃用)

将显示为 Woocommerce 3 后缀的选定变体价格:

add_filter('woocommerce_available_variation', 'display_variation_price_suffixed', 10, 3 );
function display_variation_price_suffixed( $variation_data, $product, $variation ) {
    $variation_data['price_html'] .= ' <span class="price-suffix">' . __("per kilo", "woocommerce") . '</span>';

    return $variation_data;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

If needed you can use $variation_data['attributes'] array to target specific product attributes term values in a foreach loop.

有关信息,过滤器挂钩 woocommerce_available_variation is located inside WC_Product_Variable get_available_variation() 方法。