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

问题描述 投票:0回答:1

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

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

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

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

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

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

我考虑过使用测量价格计算器,但这些插件仅适用于体积和重量等测量,而不适用于数量。

任何人都有这个问题的经验和可能的解决方案吗? 任何帮助将不胜感激。谢谢!

php wordpress woocommerce custom-fields product-price
1个回答
2
投票

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

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

1)在后端:仅针对可变产品,我们添加自定义设置字段,以显示“最低单价”。

enter image description here

2)在前端:仅对于可变产品,我们在商店、档案和单个产品页面中显示自定义的“最低单价”。

enter image description here

代码:

// 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 文件中。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.