Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Last active January 12, 2023 01:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BhargavBhandari90/fb0ad0a2bf592a53426cf1889f893d4f to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/fb0ad0a2bf592a53426cf1889f893d4f to your computer and use it in GitHub Desktop.
Add custom profile field to edit user profile
<?php
/**
* Add user profile extra fields.
*
* @param object $user
* @return void
*/
function buntywp_extra_user_profile_fields( $user ) {
$extra_field = get_user_meta( $user->ID, 'extra_field', true );
?>
<h3><?php _e( 'Extra profile fields', 'default' ); ?></h3>
<table class="form-table">
<tr>
<th><label for="extra_field"><?php _e( 'Extra Field' ); ?></label></th>
<td>
<input type="text" name="extra_field" id="extra_field" value="<?php echo esc_attr( $extra_field ); ?>" class="regular-text" /><br />
<p class="description"><?php _e( 'Description goes gere.', 'default' ); ?></p>
</td>
</tr>
</table>
<?php
}
add_action( 'edit_user_profile', 'buntywp_extra_user_profile_fields', 99 );
/**
* Save user profile extra fields.
*
* @param int $user_id
* @return void
*/
function buntywp_save_extra_user_profile_fields( $user_id ) {
if ( empty( $user_id ) ) {
return;
}
// Verify the nonce.
if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-user_' . $user_id ) ) {
return;
}
// Only allow admin.
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// Set company creator.
update_user_meta( $user_id, 'extra_field', $_POST['extra_field'] );
}
add_action( 'edit_user_profile_update', 'buntywp_save_extra_user_profile_fields' );
@pedrocamponez
Copy link

Awesome code, bro! Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment