如何在WooCommerce商品页将加入购物车按钮移至数量控件下方?
调整WooCommerce商品页加入购物车按钮位置的可行方法
方法一:使用PHP钩子(推荐,适配主题更新)
WooCommerce默认将数量控件和加入购物车按钮整合在同一模块中,我们可以通过移除默认模块、重新拆分并调整顺序来实现需求。将以下代码添加到主题的functions.php文件,或使用自定义代码插件(如Code Snippets)避免主题更新丢失:
// 移除默认的加入购物车模块(简单商品) remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); // 单独添加数量控件到价格之后,优先级15 add_action( 'woocommerce_single_product_summary', 'woocommerce_single_product_quantity', 15 ); // 单独添加加入购物车按钮到数量之后,优先级20 add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart_button_only', 20 ); // 定义仅显示加入购物车按钮的函数 function woocommerce_template_single_add_to_cart_button_only() { global $product; echo '<div class="add-to-cart-button-wrap">'; woocommerce_template_single_add_to_cart_button(); echo '</div>'; } // 定义单独显示数量控件的函数 function woocommerce_single_product_quantity() { global $product; if ( ! $product->is_sold_individually() && !in_array( $product->get_type(), ['variable', 'grouped'] ) ) { woocommerce_quantity_input( array( 'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ), 'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ), 'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1, ) ); } } // 针对可变商品的调整 remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 ); add_action( 'woocommerce_single_variation', 'woocommerce_single_variation_quantity', 15 ); add_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 ); function woocommerce_single_variation_quantity() { global $product; if ( ! $product->is_sold_individually() ) { woocommerce_quantity_input( array( 'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ), 'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ), 'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1, ) ); } }
方法二:使用CSS快速调整(适合主题自定义模板的情况)
如果PHP钩子无效,可能是主题重写了WooCommerce模板,此时可以用CSS的flexbox属性调整元素顺序。将以下代码添加到主题的自定义CSS(外观 → 自定义 → 额外CSS),并根据主题实际元素类名调整选择器:
/* 将商品摘要区域设为垂直排列的flex容器 */ .single-product-summary { display: flex; flex-direction: column; } /* 价格排第1位 */ .single-product-summary .price { order: 1; margin-bottom: 15px; } /* 数量控件排第2位 */ .single-product-summary .quantity { order: 2; margin-bottom: 15px; } /* 加入购物车按钮排第3位 */ .single-product-summary .single_add_to_cart_button { order: 3; }
提示:如果选择器不生效,可通过浏览器开发者工具(F12)查看元素的实际类名,替换上述代码中的选择器。
内容的提问来源于stack exchange,提问作者Mavis
相关产品推荐
相关产品推荐

