Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Last active November 4, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/c96a95a8cc5154398d773090b9ea9909 to your computer and use it in GitHub Desktop.
Save nfsarmento/c96a95a8cc5154398d773090b9ea9909 to your computer and use it in GitHub Desktop.
Add a custom image to WordPress User Profile
/**
*
* Add custom user profile information
*
*/
add_action( 'show_user_profile', 'ns_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'ns_show_extra_profile_fields' );
function ns_show_extra_profile_fields( $user ) { ?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr>
<th><label for="image">Profile Image</label></th>
<td>
<img src="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" style="height:50px;">
<input type="text" name="image" id="image" value="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" class="regular-text" /><input type='button' class="button-primary" value="Upload Image" id="uploadimage"/><br />
<span class="description">Please upload your image for your profile.</span>
</td>
</tr>
</table>
<?php
}
/**
* Enqueue a script in the WordPress admin user-edit.php.
*
* @param int $pagenow Hook suffix for the current admin page.
*/
function ns_selectively_enqueue_admin_script( $hook ) {
global $pagenow;
if ($pagenow != 'user-edit.php') {
return;
}
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
wp_register_script( 'profile-image', get_template_directory_uri().'/js/profile-image.js', array('jquery-core'), false, true );
wp_enqueue_script( 'profile-image' );
}
add_action( 'admin_enqueue_scripts', 'ns_selectively_enqueue_admin_script' );
/*
* Save custom user profile data
*
*/
add_action( 'personal_options_update', 'ns_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'ns_save_extra_profile_fields' );
function ns_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
if(isset($_POST['image'])) {
$imageprofile = sanitize_text_field( wp_unslash( $_POST['image'] ) );
update_user_meta( $user_id, 'image', $imageprofile );
}
}
jQuery(document).ready(function() {
jQuery(document).find("input[id^='uploadimage']").live('click', function(){
//var num = this.id.split('-')[1];
formfield = jQuery('#image').attr('name');
tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#image').val(imgurl);
tb_remove();
}
return false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment