在 WooCommerce Checkout 上为每个产品添加数量输入字段

Add Quantity Input Field on WooCommerce Checkout For Each Product

我正在尝试了解如何在结帐页面上添加数量输入字段,这样就可以让客户更改每种产品的数量。

这是我目前得到的:

add_filter( 'woocommerce_checkout_cart_item_quantity', 'qty_and_qty_change_on_checkout', 20, 3 );
function qty_and_qty_change_on_checkout( $quantity_html, $cart_item, $cart_item_key ) {

    return '<br>
    '.woocommerce_quantity_input().'
    <span class="product-quantity">
    ' . sprintf( '<b>Qty:</b> %s', $cart_item['quantity'] ) . '
    </span>';
}

但这给了我一个错误,即使 woocommerce_quantity_input() 是它的官方功能? 错误是:

Notice: Undefined index: product in /wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 1670

您没有像在 cart/cart.php 模板文件中那样将必要的参数设置到 woocommerce_quantity_input() 函数中……以下将显示一个输入字段,其中包含结帐页面中的当前数量,替换数量字符串:

add_filter( 'woocommerce_checkout_cart_item_quantity', 'qty_input_field_on_checkout', 20, 3 );
function qty_input_field_on_checkout( $quantity_html, $cart_item, $cart_item_key ) {
    $_product = $cart_item['data'];

    if ( $_product->is_sold_individually() ) {
        $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
    } else {
        $product_quantity = woocommerce_quantity_input(
            array(
                'input_name'   => "cart[{$cart_item_key}][qty]",
                'input_value'  => $cart_item['quantity'],
                'max_value'    => $_product->get_max_purchase_quantity(),
                'min_value'    => '0',
                'product_name' => $_product->get_name(),
            ),
            $_product,
            false
        );
    }

    return '<br><span class="product-quantity"><strong>' . __( 'Qty') . ': </strong></span>' . $product_quantity;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。

Now this will only allow to display the quantity field, but will not not allow to update the product quantity, as it's something else much more complicated.