Add new field to wordpress signup form
To add a new field to the WordPress signup form, you can use the register_form_tag
hook in your theme's functions.php
file. Here's an example of how you can do it:
function add_new_field_to_signup_form() {
?>
<p>
<label for="new_field">New Field:</label>
<input type="text" id="new_field" name="new_field" value="<?php echo esc_attr( $_POST['new_field'] );?>" size="20" />
</p>
<?php
}
add_action( 'register_form', 'add_new_field_to_signup_form' );
In this example, we're adding a new field called "New Field" to the signup form. The field is a text input field, and it's labeled as "New Field". The esc_attr
function is used to escape the value of the field, which is stored in the $_POST
array.
You can also use the register_form_tag
hook to add a dropdown field, checkbox, or any other type of field you want.
If you want to validate the new field, you can use the register_validate_user
hook:
function validate_new_field( $errors, $user ) {
if ( empty( $_POST['new_field'] ) ) {
$errors->add( 'new_field_error', 'New field is required.' );
}
return $errors;
}
add_action( 'register_validate_user', 'validate_new_field', 10, 2 );
In this example, we're checking if the new field is empty, and if it is, we're adding an error message to the $errors
object.
You can also use the user_register
hook to save the new field to the user's profile:
function save_new_field( $user_id ) {
if (! empty( $_POST['new_field'] ) ) {
update_user_meta( $user_id, 'new_field', sanitize_text_field( $_POST['new_field'] ) );
}
}
add_action( 'user_register', 'save_new_field' );
In this example, we're checking if the new field is not empty, and if it's not, we're saving it to the user's profile using the update_user_meta
function. The sanitize_text_field
function is used to sanitize the value of the field.
Remember to always validate and sanitize user input to prevent security vulnerabilities.