为 Woocommerce 中的可变产品设置最小单位显示价格

Set a min unit displayed price for variable products in Woocommerce

我正在 WooCommerce 中建立一个网上商店来销售医用手套。它们按单位、按盒或托盘出售。当您按盒或托盘购买时,您将获得较低的单价。

我已经尝试了一段时间,但似乎无法获得我想要的配置。

我先举个例子
产品A:
单价:1,90 欧元。
购买一盒时的单价:1,76 欧元(120 件)。
购买托盘时的单价:1,63 欧元(2880 件)。

我想要的是:
- 在存档页面上它应该显示:从 1,63 欧元起。
- 在产品页面上,用户可以 select 按单位/箱/托盘购买。
- 根据 selection,价格应自动计算。所以如果用户选择1托盘,价格应该是2880*1,63=4694,40。或者如果用户选择 2 个托盘,则价格应为 (2880*1,63)*2

我一直在尝试最小最大数量。我在变体选项卡中输入了单价并添加了最小数量和步骤。例如托盘最少 2880 个单位和 2880 个台阶。基本上它是有效的,但是...我认为如果客户在订单中看到 2880 作为数量,而不是仅仅 1 个托盘,这会让他们感到困惑。

另一种可能性是,如果我直接将总价添加到变体选项卡中,则托盘价格为 4694,40 欧元。这也有效,但是......在存档页面上它显示从 1,90 欧元起。所以他们不会直接看到如果他们按托盘购买,他们可以从 1,63 获得一个单位。

我考虑过使用 Measurement Price Calculator,但这些插件仅适用于体积和重量等测量值,而不适用于数量。

有没有人对此问题有经验和可能的解决方案? 任何帮助将不胜感激。谢谢!

您应该使用可变产品并为每个产品设置 3 个变体:

  • 每单位
  • 每盒
  • 每个托盘

1) 在后端:仅针对变量产品,我们添加了一个自定义设置字段,用于显示 "Min unit price"。

2) 在前端:仅针对可变产品,我们在商店、档案和单个产品页面中显示自定义 "Min unit price"。

代码:

// Backend: Add and display a custom field for variable products
add_action('woocommerce_product_options_general_product_data', 'add_custom_product_general_field');
function add_custom_product_general_field()
{
    global $post;

    echo '<div class="options_group hide_if_simple hide_if_external">';

    woocommerce_wp_text_input(array(
        'id'          => '_min_unit_price',
        'label'       => __('Min Unit price', 'woocommerce') ,
        'placeholder' => '',
        'description' => __('Enter the minimum unit price here.', 'woocommerce'),
        'desc_tip'    => 'true',
    ));

    echo '</div>';
}

// Backend: Save the custom field value for variable products
add_action('woocommerce_process_product_meta', 'save_custom_product_general_field');
function save_custom_product_general_field($post_id)
{
    if (isset($_POST['_min_unit_price'])){
        $min_unit_price = sanitize_text_field($_POST['_min_unit_price']);
        // Cleaning the min unit price for float numbers in PHP
        $min_unit_price = str_replace(array(',', ' '), array('.',''), $min_unit_price);
        // Save
        update_post_meta($post_id, '_min_unit_price', $min_unit_price);
    }
}

// Frontend: Display the min price with "From" prefix label for variable products
add_filter( 'woocommerce_variable_price_html', 'custom_min_unit_variable_price_html', 30, 2 );
function custom_min_unit_variable_price_html( $price, $product ) {
    $min_unit_price = get_post_meta( $product->get_id(), '_min_unit_price', true );

    if( $min_unit_price > 0 ){
        $min_price_html = wc_price( wc_get_price_to_display( $product, array( 'price' => $min_unit_price ) ) );
        $price = sprintf( __( 'From %1$s', 'woocommerce' ), $min_price_html );
    }

    return $price;
}

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