Enable decimal quantities and stock for WooCommerce products

戏子无情 提交于 2021-01-28 07:12:50

问题


I want to change the default quantity from the products, from 1 to 0,1 but I can't seem to figure it out.

I tried the following:

function custom_quantity_input_args($args, $product) {
    $args['input_value'] = 0.10;
    $args['min_value'] = 0.10;
    $args['step'] = 0.10;
    $args['pattern'] = '[0-9.]*';
    $args['inputmode'] = 'numeric';

    return $args;
}

The problem with this is that modifies the quantity input from cart as well, which isn't what I want.

To be more specific I want the following:

  1. when I go to the product page I want to show 0,1;
  2. when I go to the cart page I want to show the current quantity;

The solution I mention above shows 0,1 both in product page and in cart page.
I found another solution, but it shows the current quantity both in product and in cart which, again, it's not what I want.

Any ideas?


回答1:


Based on Decimal quantity step for specific product categories in WooCommerce answer code, try the following revisited code:

// Defined quantity arguments
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 9000, 2 );
function custom_quantity_input_args( $args, $product ) {
    if( ! is_cart() ) {
        $args['input_value'] = 0.1; // Starting value
    }
    $args['min_value']   = 0.1; // Minimum value
    $args['step']        = 0.1; // 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 ) {
    $args['quantity'] = 0.1; // 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 ) {
    $data['min_qty'] = 0.1;
        
    return $data;
}

// Enable decimal quantities (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/64861903/enable-decimal-quantities-and-stock-for-woocommerce-products

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