猿问

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

并且直接条件不起作用,我尝试了几种选择,但没有任何结果。结果是没有任何东西被添加到购物车中。我可以做什么?


MYYA
浏览 109回答 1
1回答

小唯快跑啊

该woocommerce_add_to_cart_validation钩子包含不止 1 个参数,而是 5 个参数使用wc_add_notice相反的<script>alert('hola');</script>所以你得到function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {&nbsp; &nbsp; // Set (multiple) categories&nbsp; &nbsp; $categories = array ( 'flower-arrangements', 'categorie-1' );&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // If passed & has_term&nbsp; &nbsp; if ( $passed && has_term( $categories, 'product_cat', $product_id ) ) {&nbsp; &nbsp; &nbsp; &nbsp; // Field is empty&nbsp; &nbsp; &nbsp; &nbsp; if( empty( $_POST['text_flowers_label'] ) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wc_add_notice( __( 'Please enter a value into the text flowers label', 'woocommerce' ), 'error' );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $passed = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $passed;}add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
随时随地看视频慕课网APP
我要回答