在WooCommerce单个产品页面隐藏特定可变产品的数量字段
针对特定WooCommerce产品隐藏数量字段(适配3.0+版本)
先聊聊你之前的代码为啥没生效:你的逻辑是按产品类型(variable/simple)来返回是否单独销售,但你要的是针对特定产品的控制,而且WooCommerce 3.0+对产品对象的属性调用做了改动(比如要用get_id()替代旧的id),再加上钩子优先级没设高,导致你的代码被默认行为覆盖了。
下面给你几个实用的解决方案,按需选择:
方案1:针对单个/多个特定产品ID
这个方法最直接,指定产品ID后,这些产品的数量字段会直接隐藏:
function hide_quantity_field_for_specific_products( $sold_individually, $product ) { // 替换成你需要隐藏数量字段的产品ID,多个用逗号分隔 $target_product_ids = array( 123, 456, 789 ); // 检查当前产品是否在目标列表中(WooCommerce 3.0+用get_id()获取产品ID) if ( in_array( $product->get_id(), $target_product_ids ) ) { return true; // 设置为"单独销售",自动隐藏数量字段 } return $sold_individually; // 其他产品保持原有设置 } // 把优先级设为20,确保覆盖默认的钩子行为 add_filter( 'woocommerce_is_sold_individually', 'hide_quantity_field_for_specific_products', 20, 2 );
方案2:针对特定产品类别
如果某类产品(比如"限量款")都需要隐藏数量字段,用这个方法更高效:
function hide_quantity_field_for_specific_categories( $sold_individually, $product ) { // 替换成你的目标产品类别slug,多个用逗号分隔 $target_categories = array( 'limited-edition', 'custom-made' ); // 检查产品是否属于目标类别 if ( has_term( $target_categories, 'product_cat', $product->get_id() ) ) { return true; } return $sold_individually; } add_filter( 'woocommerce_is_sold_individually', 'hide_quantity_field_for_specific_categories', 20, 2 );
方案3:自定义产品编辑选项(灵活控制)
如果需要随时在后台手动选择哪些产品隐藏数量字段,这个方法最友好——不需要改代码,直接在产品编辑页勾选即可:
第一步:添加自定义复选框到产品编辑页
// 在产品编辑的"常规"选项卡添加复选框 function add_hide_quantity_field_option() { global $post; $product = wc_get_product( $post->ID ); // 只在简单/可变产品页面显示这个选项 if ( ! $product || ! in_array( $product->get_type(), array( 'simple', 'variable' ) ) ) { return; } woocommerce_wp_checkbox( array( 'id' => '_hide_quantity_field', 'label' => __( '隐藏数量字段', 'woocommerce' ), 'description' => __( '勾选后,该产品的数量字段将在前端隐藏', 'woocommerce' ), 'value' => get_post_meta( $post->ID, '_hide_quantity_field', true ) ? 'yes' : 'no' ) ); } add_action( 'woocommerce_product_options_general_product_data', 'add_hide_quantity_field_option' );
第二步:保存自定义选项的值
// 保存产品编辑页的复选框设置 function save_hide_quantity_field_option( $post_id ) { $hide_quantity = isset( $_POST['_hide_quantity_field'] ) ? 'yes' : 'no'; update_post_meta( $post_id, '_hide_quantity_field', $hide_quantity ); } add_action( 'woocommerce_process_product_meta', 'save_hide_quantity_field_option' );
第三步:根据选项控制数量字段显示
// 读取自定义选项,决定是否隐藏数量字段 function hide_quantity_field_based_on_option( $sold_individually, $product ) { if ( get_post_meta( $product->get_id(), '_hide_quantity_field', true ) === 'yes' ) { return true; } return $sold_individually; } add_filter( 'woocommerce_is_sold_individually', 'hide_quantity_field_based_on_option', 20, 2 );
注意事项
- 以上代码都可以添加到你的主题
functions.php文件中,或者使用「Code Snippets」这类自定义代码插件(推荐,避免主题更新丢失修改)。 - 不要直接修改WooCommerce核心文件,否则插件更新后你的修改会被覆盖。
内容的提问来源于stack exchange,提问作者Firefog
相关产品推荐
相关产品推荐

