排除特定产品的Woocommerce现场验证

时间:2019-03-03 07:45:08

标签: php wordpress validation woocommerce hook-woocommerce

我有一个Woocommerce网站,每个产品都有IMEI字段。我只需要特定产品即可删除字段验证(不检查IMEI字段)。我尝试了很多方法使我无法正常工作。

这是屏幕截图:

enter image description here

和代码:

foo

1 个答案:

答案 0 :(得分:2)

您可以仅对不想验证的产品检查$ product_id。

function suwpimei_custom_fields_validation( $true, $product_id, $quantity ) {
    // Compare against the product which you don't want to validate.
    // If it matches, just bail out, return whatever is passed in $true.
    if ( $product_id == 873 ) {
        return $true;
    }

    $imei_values        = trim( $_REQUEST['imei-engraving'] );
    $imei               = trim( $imei_values );
    $chk_dup_imei[]     = $imei;
    $serial_length      = 15;
    $actual_length      = intval( strlen( $imei ) );
    $flag_continue_imei = true;
    $flag_msg_imei      = array();

    if ( empty( $imei_values ) ) {
        // empty submission.
        $flag_continue_imei = false;
        $flag_msg_imei = 'Please enter at least one IMEI.<br />';
    } else {

        if ( $actual_length != $serial_length && suwpimei_is_digits( $imei ) == 1 ) {
            $flag_continue_imei = false;
            $flag_msg_imei = $imei . ' should be ' . $serial_length . ' characters, not ' . $actual_length . '. This is not a valid IMEI entry.<br />';
        }

        if ( suwpimei_is_digits( $imei ) != 1 ) {

            $flag_continue_imei = false;
            $flag_msg_imei = $imei . ' is invalid. IMEI should be digits only: no letters, punctuation, or spaces.<br />';

        }

        if ( $actual_length == $serial_length && suwpimei_is_digits( $imei ) == 1 ) {

            // only do the suwp_check_imei when imei is 15 digits
            if ($serial_length == 15) {

                if (suwpimei_check_imei($imei) == 0) {

                    $flag_continue_imei = FALSE;
                    $flag_msg_imei = $imei . ' is not a valid IMEI entry.<br />';

                }
            }

        }

    }

    $flag_msg_string = '';
    $flag_msg_string = $flag_msg_imei;

    if ( ! $flag_continue_imei ) {
        wc_add_notice( $flag_msg_string, 'error' );
        return false;
    }

    if( ! empty ( WC()->cart->get_cart() ) ) {
        //WC()->cart->empty_cart();
        wc_add_notice( 'Only allowed 1 item in cart, please remove previous item.', 'error' );
        return false;
    }

    return true;
}
add_action( 'woocommerce_add_to_cart_validation', 'suwpimei_custom_fields_validation', 10, 3 );