我有这段代码可以让我在注册过程中添加和验证自定义字段。
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
$esp_n_1 = ( ! empty( $_POST['esp_n_1'] ) ) ? trim( $_POST['esp_n_1'] ) : '';
?>
<p>
<label for="esp_n_1"><?php _e( 'Termostato n. 1', 'mydomain' ) ?><br />
<input type="text" name="esp_n_1" id="esp_n_1" class="input" value="<?php echo esc_attr( wp_unslash( $esp_n_1 ) ); ?>" size="25" /></label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['esp_n_1'] ) || ! empty( $_POST['esp_n_1'] ) && trim( $_POST['esp_n_1'] ) == '' ) {
$errors->add( 'esp_n_1_error', __( '<strong>ERROR</strong>: You must include a Serial number.', 'mydomain' ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['esp_n_1'] ) ) {
update_user_meta( $user_id, 'esp_n_1', trim( $_POST['esp_n_1'] ) );
}
}
&#13;
但我还需要一个强制验证: 当用户提交表单时,我需要使用wordpress来检查自定义字段数据是否已经存在于表的一列中(我想通过它进行迭代),如果发现注册过程继续进行,如果没有,则会引发错误消息。
我希望有人可以帮助解决这个问题。
祝你好运
答案 0 :(得分:1)
完整的代码是:
add_action(&#39; register_form&#39;,&#39; myplugin_register_form&#39;); function myplugin_register_form(){
$esp_n_1 = ( ! empty( $_POST['esp_n_1'] ) ) ? trim( $_POST['esp_n_1'] ) : '';
?>
<p>
<label for="esp_n_1"><?php _e( 'Termostato n. 1', 'mydomain' ) ?><br />
<input type="text" name="esp_n_1" id="esp_n_1" class="input" value="<?php echo esc_attr( wp_unslash( $esp_n_1 ) ); ?>" size="25" /></label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['esp_n_1'] ) || ! empty( $_POST['esp_n_1'] ) && trim( $_POST['esp_n_1'] ) == '' ) {
$errors->add( 'esp_n_1_error', __( '<strong>ERROR</strong>: You must include a Serial number.', 'mydomain' ) );
}
global $wpdb;
$found = false;
$serialnumbers = $wpdb->get_col($wpdb->prepare("SELECT serialnumber FROM ".$wpdb->prefix."espserial", 0));
foreach ($serialnumbers as $serialnumber) {
if ($serialnumber == $_POST['esp_n_1']) {
$found = true;
break;
}
}
if (! $found) {
$errors->add( 'esp_n_1_error', __( '<strong>ERROR</strong>: You Serial .', 'mydomain' ) );
}
$found = false;
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['esp_n_1'] ) ) {
update_user_meta( $user_id, 'esp_n_1', trim( $_POST['esp_n_1'] ) );
}
}`