woocommerce_add_to_cart_validation失败

时间:2019-07-15 13:40:25

标签: php wordpress woocommerce

我正在尝试先验证用户输入,然后再将其添加到购物车数据中,但是验证始终失败,并且我不知道为什么。

add_filter( 'woocommerce_add_to_cart_validation', 
'func_validate_input', 10, 3 );
function func_validate_input( $passed, $product_id, $quantity ) {
    $dimensions_array = range(10,50);
    $val_height = (float) esc_attr($_POST['height']);
    $val_length  = (float) esc_attr($_POST['length']);
    $val_width  = (float) esc_attr($_POST['width']);

    if( ! in_array($val_height, $val_length, $val_width, $dimensions_array)) 
    {
        $passed = false;
        wc_add_notice( __( 'Please input the desired dimensions (10-50 
        centimeters))', 'cfwc' ), 'error' );
    }
    return $passed;
}

2 个答案:

答案 0 :(得分:0)

如果if末尾缺少“)”?

if( ! in_array($val_height, $val_length, $val_width, $dimensions_array)){
    $passed = false;
    wc_add_notice( __( 'Please input the desired dimensions (10-50 
    centimeters))', 'cfwc' ), 'error' );
}

答案 1 :(得分:0)

好的,我认为这是一种方法。

add_filter( 'woocommerce_add_to_cart_validation', 'func_validate_dimensions', 20, 3 
);
function func_validate_dimensions( $passed, $product_id, $quantity ) {

    if((! isset($_POST['height']) 
        || (empty($_POST['height']))) 
        || (! isset($_POST['length']) 
        || (empty($_POST['length'])) )
        || (! isset($_POST['width']) 
        || ( empty($_POST['width'])) ) ){

        $passed = false;
        wc_add_notice( __( 'Please enter desired dimensions (10-50 
        centimeters)', 'cfwc' ), 'error' );
    }
    $val_range = range(10,50);
    $val_height = esc_attr($_POST['height']);
    $val_length = esc_attr($_POST['length']);
    $val_width = esc_attr($_POST['width']);

    if (( ! in_array($val_height,$val_range)) || 
        ( ! in_array($val_length,$val_range)) || 
        ( ! in_array($val_width,$val_range))){

        $passed = false;
        wc_add_notice( __( 'Please enter desired dimensions (10-50 
        centimeters)', 'cfwc' ), 'error' );
        }
    return $passed;
}