Skip to content

Instantly share code, notes, and snippets.

@spigotdesign
Last active September 26, 2022 04:38
Show Gist options
  • Save spigotdesign/4716763 to your computer and use it in GitHub Desktop.
Save spigotdesign/4716763 to your computer and use it in GitHub Desktop.
Add WordPress image uploader to user profile.
/*
* Add custom user profile information
*
*/
add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );
function my_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 }
/*
* Script for saving profile image
*
*/
add_action('admin_head','my_profile_upload_js');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
function my_profile_upload_js() { ?>
<script type="text/javascript">
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;
});
});
</script>
<?php }
/*
* Save custom user profile data
*
*/
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
function my_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
/* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */
update_usermeta( $user_id, 'image', $_POST['image'] );
}
@PhilJolley
Copy link

Could you explain more about what you enqueued exactly when you called this:

wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');

Thank you.

@spigotdesign
Copy link
Author

It's been a while since coding this, but those are WP media uploader scripts that are getting loaded from core.

@musakhan17
Copy link

Where do you think I should add the script part of this document? I am trying to add the profile picture option in a form.

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