As a website owner, you may want to collect additional information from your users beyond their basic profile details. WordPress provides a straightforward way to add custom fields to a user’s profile, allowing you to capture and store the information you need. In this article, we’ll show you how to add extra fields to users in the WordPress backend.
Step 1: Create a Custom Field
The first step is to create a custom field that will be used to capture the additional information. You can do this by adding the following code to your theme’s functions.php file or a custom plugin:
function wpd_add_user_custom_field( $user ) {
?>
<h3><?php _e('Custom Information'); ?></h3>
<table class="form-table">
<tr>
<th>
<label for="custom_field"><?php _e('Custom Field'); ?>
</label></th>
<td>
<input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr( get_the_author_meta( 'custom_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e('Please enter your custom field.'); ?></span>
</td>
</tr>
</table>
<?php
}
add_action( 'show_user_profile', 'wpd_add_user_custom_field' );
add_action( 'edit_user_profile', 'wpd_add_user_custom_field' );
This code adds a custom field to the user profile page in the WordPress backend. It displays a text input box where users can enter their custom information. You can modify the code to include different types of custom fields, such as checkboxes, dropdowns, or text areas.
Step 2: Save the Custom Field
After creating the custom field, you need to save the user’s input. You can do this by adding the following code to your theme’s functions.php file or a custom plugin:
function wpd_save_user_custom_field( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'custom_field', $_POST['custom_field'] );
}
add_action( 'personal_options_update', 'wpd_save_user_custom_field' );
add_action( 'edit_user_profile_update', 'wpd_save_user_custom_field' );
This code saves the user’s custom field to the database when the profile is updated. It uses the update_user_meta() function to store the value of the custom field. You can modify the code to save different types of custom fields.
Step 3: Display the Custom Field
After saving the custom field, you may want to display it on the frontend of your website. You can do this by adding the following code to your theme’s template files:
<?php echo get_the_author_meta( 'custom_field', $user->ID ); ?>
This code retrieves the value of the custom field and displays it on the frontend of your website.
Conclusion
Adding extra fields to users in the WordPress backend is a powerful feature that can help you capture the information you need from your users. With a few lines of code, you can create custom fields, save the user’s input, and display the information on the frontend of your website.