如何为WooCommerce全页面添加Quantity Field(Storefront主题)
让WooCommerce在首页及普通页面显示商品数量输入框
原代码仅在商店页面生效,核心原因是绑定了woocommerce_after_shop_loop_item钩子——这个钩子仅在商店商品循环场景下触发。要让首页、普通页面的商品也显示数量输入框,需要调整钩子绑定逻辑,并适配不同页面的商品展示结构。
修改后的完整代码
function custom_quantity_field_for_all_product_loops() { // 仅在产品类内容的非单品详情页执行 if ( ! is_product() && get_post_type() === 'product' ) { $product = wc_get_product( get_the_ID() ); // 排除单独售卖、非简单产品、不可购买的商品 if ( ! $product->is_sold_individually() && $product->is_type( 'simple' ) && $product->is_purchasable() ) { woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) ); } } } // 绑定多场景钩子,覆盖商店循环、首页/普通页面的商品展示 add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_for_all_product_loops', 15 ); add_action( 'woocommerce_after_add_to_cart_button', 'custom_quantity_field_for_all_product_loops', 15 ); function custom_add_to_cart_quantity_handler() { wc_enqueue_js( ' jQuery( "body" ).on( "click", ".quantity input", function() { return false; }); jQuery( "body" ).on( "change input", ".quantity .qty", function() { var add_to_cart_button = jQuery( this ).closest( ".product, .product-type-simple" ).find( ".add_to_cart_button" ); // 更新AJAX加购的数量参数 add_to_cart_button.attr( "data-quantity", jQuery( this ).val() ); // 更新非AJAX加购的链接参数 add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() ); }); ' ); } add_action( 'wp_enqueue_scripts', 'custom_add_to_cart_quantity_handler' );
关键修改说明
- 扩展钩子范围:新增
woocommerce_after_add_to_cart_button钩子绑定,该钩子会在所有产品的加购按钮后触发,覆盖首页、普通页面的商品展示场景。 - 优化产品判断:用
$product->is_type('simple')替代原代码的字符串比较,符合WooCommerce官方规范,避免类型判断出错。 - 适配页面结构:调整jQuery选择器为
closest(".product, .product-type-simple"),兼容不同页面中产品块的类名差异,确保能精准定位加购按钮。 - 规范脚本加载:将JS加载钩子从
init改为wp_enqueue_scripts,这是WordPress加载前端脚本的标准时机,避免脚本过早加载导致的DOM未就绪问题。
使用方式
将上述代码添加到Storefront主题的functions.php文件,或通过代码片段插件(如Code Snippets)导入,保存后刷新页面即可生效。
内容的提问来源于stack exchange,提问作者DeveloparAndMe
相关产品推荐
相关产品推荐

