关于 WooCommerce 结账页面的定制内容在网上有大量讨论。为什么呢?因为结账页面无疑是任何 WooCommerce 网站的关键页面!提升用户体验始终是设计和优化的重点。
接下来,我们将编写一个代码,在结账页面的每个产品旁边添加一个数量输入框。
这样一来,如果用户在结账时需要调整数量,就可以方便地完成;或者,当你决定取消购物车页面并直接将顾客带到结账页面时,这也会非常有用。
通过以下代码,你可以在结账页面的每个产品旁边添加一个数量输入框,同时还需要编写一个 "listener",以确保在数量变更后结账页面自动刷新并更新总价。
PHP代码:在 WooCommerce 结账页面显示产品数量选择器
需要注意的是,这里还需要隐藏 WooCommerce 默认在产品名称旁边显示的数量字符串(例如 "产品名 x1"、"产品名 x2"、"产品名 x3" 等)。代码段的第一行就可以实现这一功能。
// 结账页修改产品数量
add_filter( 'woocommerce_checkout_cart_item_quantity', '__return_empty_string' );
add_filter( 'woocommerce_cart_item_subtotal', 'pt_checkout_item_quantity_input', 9999, 3 );
function pt_checkout_item_quantity_input( $product_quantity, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
$product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$product_quantity = woocommerce_quantity_input( array(
'input_name' => 'shipping_method_qty_' . $product_id,
'input_value' => $cart_item['quantity'],
'max_value' => $product->get_max_purchase_quantity(),
'min_value' => '0',
), $product, false );
$product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
}
return $product_quantity;
}
add_action( 'woocommerce_checkout_update_order_review', 'pt_update_item_quantity_checkout' );
function pt_update_item_quantity_checkout( $post_data ) {
parse_str( $post_data, $post_data_array );
$updated_qty = false;
foreach ( $post_data_array as $key => $value ) {
if ( substr( $key, 0, 20 ) === 'shipping_method_qty_' ) {
$id = substr( $key, 20 );
WC()->cart->set_quantity( $post_data_array['product_key_' . $id], $post_data_array[$key], false );
$updated_qty = true;
}
}
if ( $updated_qty ) WC()->cart->calculate_totals();
}
还没有评论呢,快来抢沙发~