【问题标题】:Add to cart validation based on category and custom textfield in WooCommerce根据 WooCommerce 中的类别和自定义文本字段添加到购物车验证
【发布时间】:2020-10-24 17:44:09
【问题描述】:

我正在使用 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 );

直接条件不起作用,我尝试了几个选项,没有任何效果。结果是没有任何东西添加到购物车中。我能做什么?

【问题讨论】:

    标签: php wordpress validation woocommerce categories


    【解决方案1】:
    • woocommerce_add_to_cart_validation 挂钩包含 5 个而不是 1 个参数
    • 使用wc_add_notice对面&lt;script&gt;alert('hola');&lt;/script&gt;

    所以你得到

    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 );
    

    【讨论】:

    • 天才!它对我来说非常有效。它还没有接近解决方案,我从没想过在 if 中使用了 $passed。我有疑问,尝试更改条件中 is_product 传递的 $ ,但这不起作用。为什么它与 $ 传递一起工作?谢谢!
    • 1) Is_product - 在单个产品页面上返回 true。但是,您还可以在存档页面上添加到购物车按钮。 2) 确保函数中始终至少有 1 个return,而无需满足条件。否则,可能永远无法到达return
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2016-10-21
    • 2019-10-15
    • 2018-06-30
    • 2021-04-21
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多