Phone and Company Fields in User Profiles
Adds Phone and Company fields to user profiles, editable by the user and by administrators.
Opens WPIDE on
Code
// Meta key => label.
$wpide_profile_fields = array(
'wpide_phone' => 'Phone',
'wpide_company' => 'Company',
);
$wpide_profile_fields_render = function ( $user ) use ( $wpide_profile_fields ) {
echo '<h2>Contact Details</h2><table class="form-table" role="presentation">';
foreach ( $wpide_profile_fields as $key => $label ) {
printf(
'<tr><th><label for="%1$s">%2$s</label></th><td><input type="text" class="regular-text" name="%1$s" id="%1$s" value="%3$s"></td></tr>',
esc_attr( $key ),
esc_html( $label ),
esc_attr( get_user_meta( $user->ID, $key, true ) )
);
}
echo '</table>';
};
add_action( 'show_user_profile', $wpide_profile_fields_render );
add_action( 'edit_user_profile', $wpide_profile_fields_render );
// WordPress verifies the profile form nonce before these actions run.
$wpide_profile_fields_save = function ( $user_id ) use ( $wpide_profile_fields ) {
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return;
}
foreach ( array_keys( $wpide_profile_fields ) as $key ) {
if ( isset( $_POST[ $key ] ) ) {
update_user_meta( $user_id, $key, sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) );
}
}
};
add_action( 'personal_options_update', $wpide_profile_fields_save );
add_action( 'edit_user_profile_update', $wpide_profile_fields_save );
Notes
Read a value in templates with get_user_meta( $user_id, 'wpide_phone', true ).
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.