基于 WooCommerce 中的类别和自定义文本字段添加到购物车验证

Add to cart validation based on category and custom textfield in WooCommerce

我正在使用 WooCommerce 并在产品页面中添加两个新字段,当我想使用 woocommerce_add_to_cart_validation 进行验证时,它工作得很好。

但事实证明,我只想要产品中包含特定类别的那些字段。

字段仅在“flower-arrangements”类别中显示,因此我只想在显示字段时应用验证。

我有这个:

function garo_validate_custom_field( $passed ) {
    global $post;

     if (is_product() && has_term( 'flower-arrangements', 'product_cat', $post->ID ) ) {  
     if( empty( $_POST['text_flowers_label'] ) ) {
     wc_add_notice( __( 'Please enter a value into the text flowers label', 'cfwc' ), 'error' );
     $passed = false;
     echo "<script>alert('hola');</script>";
     }
     return $passed;
  }
}
add_filter( 'woocommerce_add_to_cart_validation', 'garo_validate_custom_field', 10 );

而且直接条件不行,我试了好几个选项都没用。结果是什么都没有添加到购物车。我能做什么?

  • woocommerce_add_to_cart_validation 钩子包含 5 个参数而不是一个
  • 使用 wc_add_notice 相反 <script>alert('hola');</script>

所以你得到

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Set (multiple) categories
    $categories = array ( 'flower-arrangements', 'categorie-1' );
    
    // If passed & has_term
    if ( $passed && has_term( $categories, 'product_cat', $product_id ) ) {
        // Field is empty
        if( empty( $_POST['text_flowers_label'] ) ) {
            wc_add_notice( __( 'Please enter a value into the text flowers label', 'woocommerce' ), 'error' );
            $passed = false;
        }
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );