为多个活动变体定制 Woocommerce 可变产品价格范围

Custom Woocommerce variable product price range for more than one active variation

我正在使用我在 Internet 上找到的这个脚本来删除价格范围并仅显示 WooCommerce/WordPress 中可变产品的最低价格,语法如下:From US$ xxxx

我希望脚本在变量产品只有一种变体时例外地执行同样的操作。 有一个自动 cron(bash + SQL 脚本)可以删除不可用的产品。有时它会留下只有一个变体的可变产品,并且列出这个变体并标明 "From US$ xxx" 的价格看起来很荒谬,因为只有一个变体)。

您将如何添加一个条件以仅将 From US$ xxx 应用于具有多个变体的可变产品。我的主要目标是在 catalog/category/shop 页面上使用它,因为已经有一个片段可以从可变的单一产品页面中删除价格范围。谢谢

add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_310', 10, 2 );
function bbloomer_variation_price_format_310( $price, $product ) {

// 1. Find the minimum regular and sale prices

$min_var_reg_price = $product->get_variation_regular_price( 'min', true );
$min_var_sale_price = $product->get_variation_sale_price( 'min', true );

// 2. New $price

if ( $min_var_sale_price ) {
$price = sprintf( __( 'From %1$s', 'woocommerce' ), wc_price( $min_var_reg_price ) );
}

// 3. Return edited $price

return $price;
}

// Display Price For Variable Product With Same Variations Prices
add_filter('woocommerce_available_variation', function ($value, $object = null, $variation = null) {
    if ($value['price_html'] == '') {
        $value['price_html'] = '<span class="price">' . $variation->get_price_html() . '</span>';
    }
    return $value;
}, 10, 3);

在您的第一个函数中计算可见子项将使您能够实现这一目标。我还重新访问了你的第二个函数,它应该被命名为:

add_filter( 'woocommerce_variable_price_html', 'custom_variation_price_html', 20, 2 );
function custom_variation_price_html( $price_html, $product ) {
    $visible_children = $product->get_visible_children();
    if( count($visible_children) <= 1 ) return $price_html; // Exit if only one variation

    $regular_price_min = $product->get_variation_regular_price( 'min', true );
    $sale_price_min = $product->get_variation_sale_price( 'min', true );

    if ( $sale_price_min ) 
        $price_html = __( 'From', 'woocommerce' ).' '.wc_price( $regular_price_min );

    return $price_html;
}

add_filter('woocommerce_available_variation', 'custom_available_variation', 20, 3 ) ;
function custom_available_variation( $args, $product, $variation ) {
    if( $args['price_html'] == '' )
        $args['price_html'] = '<span class="price">' . $variation->get_price_html() . '</span>';
    
    return $args;
}

此代码在您的活动子主题(或主题)的 function.php 文件中。

已测试并有效。