Woocommerce注册表单验证无效

时间:2014-06-16 13:47:42

标签: php wordpress forms validation woocommerce

我在我的woocommerce注册表中添加了一些新字段,但我无法验证这些新字段。

有我的新字段

add_action('register_form','myplugin_register_form');
function myplugin_register_form (){
    $first_name = ( isset( $_POST['first_name'] ) ) ? $_POST['first_name']: '';
    $last_name = ( isset( $_POST['last_name'] ) ) ? $_POST['last_name']: '';
    ?>
    <div class="row">
        <div class="col-md-4">
            <label for="first_name">Prénom <span class="required">*</span></label>
            <input type="text" class="input-text" name="first_name" id="first_name" value="<?php if ( ! empty( $_POST['first_name'] ) ) echo esc_attr( $_POST['first_name'] ); ?>" />
        </div>
        <div class="col-md-4">
            <label for="last_name">Nom <span class="required">*</span></label>
            <input type="text" class="input-text" name="last_name" id="last_name" value="<?php if ( ! empty( $_POST['last_name'] ) ) echo esc_attr( $_POST['last_name'] ); ?>" />
        </div>
    </div>
    <?php
}

这是我根据wordpress codex https://codex.wordpress.org/Customizing_the_Registration_Form

进行验证的过滤器
function myplugin_registration_errors ($errors, $sanitized_user_login, $user_email) {

    if ( empty( $_POST['first_name'] ) )
        $errors->add( 'first_name_error', __('<strong>ERROR</strong>: You must include a first name.','mydomain') );

    return $errors;
}

当我提交表单时,如果没有字段$ _POST ['first_name'],它就会毫无错误地传递。

最好的方法是什么?

感谢您的帮助

2 个答案:

答案 0 :(得分:4)

请在主题/儿童主题的函数中写下此代码.php

/**
 * Validate the extra register fields.
 *
 * @param  string $username          Current username.
 * @param  string $email             Current email.
 * @param  object $validation_errors WP_Error object.
 *
 * @return void
 */
function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {

    if ( isset( $_POST['first_name'] ) && empty( $_POST['first_name'] ) ) {
        $validation_errors->add( 'first_name_error', __( '<strong>Error</strong>: First Name is required!.', 'woocommerce' ) );
    }

    if ( isset( $_POST['last_name'] ) && empty( $_POST['last_name'] )  ) {
        $validation_errors->add( 'last_name_error', __( '<strong>Error</strong>: Last Name is required!.', 'woocommerce' ) );
    }
}

add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );

答案 1 :(得分:2)

如果您查看woocommerce-fundtions.php,请检查$woocommerce->error -count() == 0,然后继续。所以,而不是向wordpress $errors添加错误,我会向Woocommerce添加错误,例如$woocommerce->add_error( $reg_errors->get_error_message() )

所以代码是

add_filter('registration_errors', 'myplugin_registration_errors' ), 10, 3);

function myplugin_registration_errors($errors, $sanitized_user_login, $user_email) {
    global $woocommerce;

    if ( empty( $_POST['first_name'] ) )
        $woocommerce->add_error( 'first_name_error', __('<strong>ERROR</strong>: You must include a first name.','mydomain') );

    return $errors;
}
相关问题