Mặc định ô nhập số lượng của Woocommerce chỉ có phép số nguyên từ 1,2,3… Nhưng do nhiều nhu cầu khác nhau mà cần nhập số thập phân vào đó để tính giá.

Ví dụ bạn làm site bán mực tươi chẳng hạn. Giá hiển thị là 250.000/kg nhưng khách chỉ muốn mua 0.5kg thôi thì sẽ làm thế nào? Đoạn code sau sẽ giúp bạn làm được điều đó

Bạn hãy chèn đoạn code sau vào file functions.php của theme đang sử dụng là được

// Simple products
add_filter( 'woocommerce_quantity_input_args', 'devvn_woocommerce_quantity_input_args', 10, 2 );
function devvn_woocommerce_quantity_input_args( $args, $product ) {
    if ( is_singular( 'product' ) ) {
        $args['input_value']   = 1; // Starting value (we only want to affect product pages, not cart)
    }
    $args['max_value']     = 80;  // Maximum value
    $args['min_value']     = 0.5;  // Minimum value
    $args['step']     = 0.5;  // Quantity steps
    return $args;
}

// Variations
add_filter( 'woocommerce_available_variation', 'devvn_woocommerce_available_variation' );
function devvn_woocommerce_available_variation( $args ) {
    $args['max_qty'] = 80;     // Maximum value (variations)
    $args['min_qty'] = 0.5; // Minimum value (variations)
    return $args;
}

// Removes the WooCommerce filter, that is validating the quantity to be an int
remove_filter('woocommerce_stock_amount', 'intval');

// Add a filter, that validates the quantity to be a float
add_filter('woocommerce_stock_amount', 'floatval');

// Add unit price fix when showing the unit price on processed orders
add_filter('woocommerce_order_amount_item_total', 'devvn_unit_price_fix', 10, 5);
function devvn_unit_price_fix($price, $order, $item, $inc_tax = false, $round = true) {
    $qty = (!empty($item['qty']) && $item['qty'] != 0) ? $item['qty'] : 1;
    if($inc_tax) {
        $price = ($item['line_total'] + $item['line_tax']) / $qty;
    } else {
        $price = $item['line_total'] / $qty;
    }
    $price = $round ? round( $price, 2 ) : $price;
    return $price;
}

Hiểu các thông số trên như sau.

  • Giá trị mặc định là 1
  • Giá trị max là 80
  • Giá trị min là 0.5
  • Bước nhảy cho mỗi lần ấn + –  là 0.5

Các bạn hoàn toàn có thể thay đổi các giá trị trên. Ví dụ không muốn giới hạn số lượng thì có thể bỏ đi đoạn $args[‘max_value’]

Và trong hình trên bạn có thấy /kg chứ? Nếu hay hãy like và share bài viết để nhiều người biết đến nhé. Cảm ơn các bạn

Nguồn: levantoan.com