WooCommerce - 隐藏特定变体

WooCommerce - Hide specific variations

如何从产品页面的下拉菜单中隐藏变体,但仍然可以通过 WooCommerce URL 优惠券购买?

如果我不激活变体,它会从下拉列表中隐藏,但我会在购物车中收到消息 "This product can not be purchased"。我只是想从列表中隐藏它,而不是完全禁用它。

非常感谢任何帮助。

谢谢!

以下解决方案适用于我的主题,但您是 运行 Bootstrap,因此您可能遇到问题。

我们将修改您要使用 hidden 属性隐藏的选项的 option 标记。获取以下代码并将其添加到您的主题 functions.php 或自定义插件中:

自定义代码

function custom_woocommerce_dropdown_variation_attribute_options_html( $html, $args )
{
    $product = $args[ 'product' ];
    $attribute = $args[ 'attribute' ];
    $terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );
    $options = $args[ 'options' ];
    if ( empty( $options ) && !empty( $product ) && !empty( $attribute ) ) {
        $attributes = $product->get_variation_attributes();
        $options = $attributes[ $attribute ];
    }

    foreach ( $terms as $term ) {
        if ( in_array( $term->slug, $options ) && ***SOME CONDITION***) {
            $html = str_replace( '<option value="' . esc_attr( $term->slug ) . '" ', '<option hidden value="' . esc_attr( $term->slug ) . '" ', $html );
        }
    }
    return $html;
}
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'custom_woocommerce_dropdown_variation_attribute_options_html', 10, 2 );

请注意,某些浏览器无法识别 hidden 属性。如果您想要完全的跨浏览器兼容性,您需要查看 How to hide a <option> in a <select> menu with CSS? 上的答案。添加 css 属性 style="display:none" 也可能适用于某些浏览器。

高级自定义字段

现在,在上面的代码中,我写了 ***SOME CONDITION***。这个条件需要检查一个选项是否应该被隐藏。要添加此信息,我们需要为属性创建一个自定义字段。您可以手动执行此操作,但我使用高级自定义字段插件 (ACF) 执行此操作。

  1. Products->Attributes 中创建一个产品属性。勾选 Enable Archives? 并设为 type "Select"。然后在Configure terms.
  2. 下添加属性terms
  3. 安装 Advanced Custom Fields 到您的 WordPress。
  4. 创建一个新的字段组。
  5. 在字段组中创建规则 显示此字段组 if Taxonomy Term is equal to Product **your attribute**.
  6. 在字段组中创建一个带有字段标签='hidden'、字段类型='True / False'的字段并根据需要设置其他设置。
  7. Publish/Update 字段组。
  8. 返回到您在第 1 步中创建的要隐藏的术语。您应该有一个复选框来 select 是否应隐藏该属性。勾选所有适用项。
  9. 使用由产品属性构成的变体创建可变产品。
  10. 在自定义代码中,删除 ***SOME CONDITION*** 并将其替换为 get_field( 'hidden', $term ) )。这是一个 ACF 函数,它将获取该属性的 tern 的 'hidden' 字段的值。

毕竟,您勾选为隐藏的条款不应出现在产品页面的下拉列表中。在我的示例中,您可以看到下拉列表中缺少 green

我在这里很新,一般不会玩代码,但我在定制器中使用 css 来隐藏一个名为 "Student:"

的变体
.postid-403 option[value=Student]{display: none;}

postid-403 标识我的产品页面。这似乎有效。有什么理由不这样做吗?