如何在WooCommerce购物车页面隐藏/禁用可下载商品的数量字段
针对WooCommerce可下载/虚拟商品禁用数量字段的解决方案
1. 商品页面隐藏/锁定数量输入框
将以下代码添加到主题functions.php文件或自定义代码片段插件中,自动识别可下载/虚拟商品,隐藏数量字段并强制默认数量为1:
// 针对可下载/虚拟商品隐藏数量字段 add_action( 'woocommerce_before_add_to_cart_quantity', 'hide_quantity_for_downloadable_products' ); function hide_quantity_for_downloadable_products() { global $product; if ( $product->is_downloadable() || $product->is_virtual() ) { echo '<style>.quantity { display: none !important; }</style>'; wc_enqueue_js( 'jQuery(".single_add_to_cart_button").data("quantity", 1);' ); } } // 锁定可下载/虚拟商品的数量输入为1,禁止修改 add_filter( 'woocommerce_quantity_input_args', 'lock_quantity_for_downloadable_products', 10, 2 ); function lock_quantity_for_downloadable_products( $args, $product ) { if ( $product->is_downloadable() || $product->is_virtual() ) { $args['min_value'] = 1; $args['max_value'] = 1; $args['input_value'] = 1; } return $args; }
2. 购物车&结账页面强制数量不可修改
防止用户通过URL参数或其他途径修改数量,添加以下代码确保购物车中可下载/虚拟商品的数量始终为1:
// 购物车页面强制可下载/虚拟商品数量为1 add_action( 'woocommerce_before_calculate_totals', 'force_single_quantity_in_cart' ); function force_single_quantity_in_cart( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { $product = $cart_item['data']; if ( $product->is_downloadable() || $product->is_virtual() ) { $cart->set_quantity( $cart_item_key, 1 ); } } } // 结账页面移除数量修改控件 add_filter( 'woocommerce_cart_item_quantity', 'remove_quantity_controls_checkout', 10, 3 ); function remove_quantity_controls_checkout( $product_quantity, $cart_item_key, $cart_item ) { $product = $cart_item['data']; if ( $product->is_downloadable() || $product->is_virtual() ) { return '1'; } return $product_quantity; }
使用说明
- 代码可添加到当前主题
functions.php末尾,推荐用代码片段插件(如Code Snippets)管理,避免主题更新丢失代码; - 代码会自动匹配所有标记为「可下载」或「虚拟」的商品,无需逐个设置。
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

