WooCommerce中特定产品类别的小数步长 [英] Decimal quantity step for specific product categories in WooCommerce

查看:71
本文介绍了WooCommerce中特定产品类别的小数步长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调整特定产品类别的数量步长,以允许十进制数字(具体为0.5步长).有点像设置数量Woocommerce回答中产品级别的最小,最大和步长,但要指定特定的小数步长和特定的产品类别.

I would like to adjust quantity step for specific product categories to allow decimal numbers (0.5 steps specifically). A bit like in Set quantity minimum, maximum and step at product level in Woocommerce answer but for a specific decimal step and specific product categories.

欢迎任何帮助.

推荐答案

要使其适用于小数步长的特定产品类别,您不需要在产品级别进行设置…在以下代码中,您将必须在第一个代码中进行设置发挥产品类别的作用(可以是ID,s或名称):

To make it work for specific product categories for decimal quantity step you don't need settings at product level… In following code you will have to set on the first function your product categories (can be terms ids, slugs or names):

// custom conditional function (check for product categories)
function enabled_decimal_quantities( $product ){
    $targeted_terms = array(12, 16); // Here define your product category terms (names, slugs ord Ids)

    return has_term( $targeted_terms, 'product_cat', $product->get_id() );
}

// Defined quantity arguments 
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 9000, 2 );
function custom_quantity_input_args( $args, $product ) {
    if( enabled_decimal_quantities( $product ) ) {
        if( ! is_cart() ) {
            $args['input_value'] = 0.5; // Starting value
        }
        $args['min_value']   = 0.5; // Minimum value
        $args['step']        = 0.5; // Quantity steps
    }
    return $args;
}

// For Ajax add to cart button (define the min value)
add_filter( 'woocommerce_loop_add_to_cart_args', 'custom_loop_add_to_cart_quantity_arg', 10, 2 );
function custom_loop_add_to_cart_quantity_arg( $args, $product ) {
    if( enabled_decimal_quantities( $product ) ) {
        $args['quantity'] = 0.5; // Min value
    }
    return $args;
}

// For product variations (define the min value)
add_filter( 'woocommerce_available_variation', 'filter_wc_available_variation_price_html', 10, 3);
function filter_wc_available_variation_price_html( $data, $product, $variation ) {
    if( enabled_decimal_quantities( $product ) ) {
        $data['min_qty'] = 0.5;
    }
    return $data;
}

// Enable decimal quantities for stock (in frontend and backend)
remove_filter('woocommerce_stock_amount', 'intval');
add_filter('woocommerce_stock_amount', 'floatval');

代码进入活动子主题(或活动主题)的functions.php文件中.经过测试,可以正常工作.

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

这篇关于WooCommerce中特定产品类别的小数步长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆