Decimal quantity step for specific product categories in WooCommerce

给你一囗甜甜゛ 提交于 2021-01-05 09:13:06

问题


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.

Any help is welcome.


回答1:


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

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



来源:https://stackoverflow.com/questions/64813870/decimal-quantity-step-for-specific-product-categories-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!