首页 > 解决方案 > woocommerce_add_to_cart_validation 失败

问题描述

我试图在将用户输入添加到购物车数据之前对其进行验证,但验证总是失败,我不知道为什么。

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

标签: phpwordpresswoocommerce

解决方案


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

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

推荐阅读