set avatar of user front side wordpress

Posted: June 5, 2015 in Uncategorized
Tags: , , , , , ,

Recently I am working on registratoin page in which user can upload his/her profile.
My strategy is after upload profile picture,I will set picture as attachment and then add that attachment id in user meta :).
Step 1 : First I add image as attachment here is the code.

if(isset($_FILES[‘profile_picture’]) && !empty($_FILES[‘profile_picture’][‘name’])){

$uploadedfile = $_FILES[‘profile_picture’];
//$upload_name = $_FILES[‘upload_image’][‘name’].’_’.rand();
$upload_name = $_FILES[‘profile_picture’][‘name’];

$uploads = wp_upload_dir();
$filepath = $uploads[‘path’].”/$upload_name”;

if ( ! function_exists( ‘wp_handle_upload’ ) )
{
require_once( ABSPATH . ‘wp-admin/includes/file.php’ );
}
require_once( ABSPATH . ‘wp-admin/includes/image.php’ );
$upload_overrides = array( ‘test_form’ => false );
//$attach_id = media_handle_upload( $file, $new_post );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
//print_r($movefile);
if ( $movefile && !isset( $movefile[‘error’] ) ) {

$file = $movefile[‘file’];
$url = $movefile[‘url’];
$type = $movefile[‘type’];

//media_handle_upload( $file_handler, 0 );
$attachment = array(
‘post_mime_type’ => $type ,
‘post_title’ => $upload_name,
‘post_content’ => ‘Image for ‘.$upload_name,
‘post_status’ => ‘inherit’
);

$attach_id=wp_insert_attachment( $attachment, $file, 0);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
//echo $postid = wp_insert_post( $my_post );

//add_post_meta($postid, “file”, $file);

//echo $updated_gallery = serialize($result);

} else {
echo $movefile[‘error’];
}

//$attachid_arr = array($attach_id);

}

Step 2 : after get attachment id, with the help of plugin called : Wp User Avatar.In that Just pass your attachment id in following code….

delete_metadata(‘post’, null, ‘_wp_attachment_wp_user_avatar’, $user_id, true);
update_user_meta($user_id, ‘_wp_attachment_wp_user_avatar’, $attach_id);
update_user_meta($user_id, $wpdb->get_blog_prefix($blog_id) . ‘user_avatar’, $attach_id);

Advertisements
Comments
  1. anandnayi says:

    Really very nice!!!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s