Skip to content

Instantly share code, notes, and snippets.

@gdarko
Last active March 11, 2023 21:11
Show Gist options
  • Save gdarko/f858686eae428c1e56076e5e47b1b6d4 to your computer and use it in GitHub Desktop.
Save gdarko/f858686eae428c1e56076e5e47b1b6d4 to your computer and use it in GitHub Desktop.
WordPress Custom Profile Image Ajax Upload
.upload-thumb {
display: inline-block;
width: 120px;
height: 120px;
overflow: hidden;
background: #e2e2e2;
border: 1px solid #cdcdcd;
line-height: 120px;
margin-bottom: 10px;
}
.upload-thumb.cover {
width: 500px;
}
.file-upload {
position: relative;
overflow: hidden;
}
.file-upload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
(function($){
$('input[type=file][data-ajaxed=Y]').on('change', function(event) {
files = event.target.files;
var cont = $(this).attr('data-cont');
var name = $(this).attr('name');
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
data.append('partner_info_post_id', $(this).closest('form').find("#partner_info_post_id").val() );
data.append('type', $(this).data('type'));
$(cont).html('<img src="/assets/images/preloader.gif" />');
$.ajax({
url: '/wp-admin/admin-ajax.php?action=file_upload&fname='+name, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: data, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
dataType: 'json',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
if(data.error)
{
alert(data.error);
}
else
{
$(cont).html('<img src="'+data.src+'" style="max-width:100%;" />');
$('[name='+name+'_aid]').val(data.aid);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
alert('ERRORS: ' + textStatus);
$(cont).html('error');
// STOP LOADING SPINNER
}
});
});
})(jQuery);
<?php
add_action('wp_ajax_file_upload', 'dg_file_upload_handler' );
function dg_file_upload_handler()
{
//Get the file
$f = 0;
$_FILES[$f] = $_FILES[0];
$user = new WP_User(get_current_user_id());
$json['status'] = 'error';
//Check if the file is available && the user is logged in
if (!empty($_FILES[$f]) && $user->ID > 0) {
$json = array();
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
//Handle the media upload using WordPress helper functions
$attachment_id = media_handle_upload($f, 0);
$json['aid'] = $attachment_id;
//If error
if (is_wp_error($attachment_id)) {
$json['error'] = "Error.";
} else {
//delete current
$profile_image = get_user_meta($user->ID, 'profile_image', true);
if ($profile_image) {
$profile_image = json_decode($profile_image);
if (isset($profile_image->attachment_id)) {
wp_delete_attachment($profile_image->attachment_id, true);
}
}
//Generate attachment in the media library
$attachment_file_path = get_attached_file($attachment_id);
$data = wp_generate_attachment_metadata($attachment_id, $attachment_file_path);
//Get the attachment entry in media library
$image_full_attributes = wp_get_attachment_image_src($attachment_id, 'full');
$image_thumb_attributes = wp_get_attachment_image_src($attachment_id, 'smallthumb');
$arr = array(
'attachment_id' => $attachment_id,
'url' => $image_full_attributes[0],
'thumb' => $image_thumb_attributes[0]
);
//Save the image in the user metadata
update_user_meta($user->ID, 'profile_image', json_encode($arr));
$json['src'] = $arr['thumb'];
$json['status'] = 'ok';
}
}
//Output the json
die(json_encode($json));
}
<?php
$user_id = get_current_user_id();
$profile_img = @json_decode(get_user_meta($user_id, 'profile_image', true));
$profile_img = !$profile_img ? '' : $profile_img;
?>
<div class="profile-picture">
<div class="upload-thumb profile_image">
<img src="<?php echo $profile_img->thumb; ?>">
</div>
<div>
<div class="file-upload button">
<span>Upload</span>
<input data-type="image" type="file" data-ajaxed="Y" data-cont=".profile_image" name="image" class="upload" />
<input type="hidden" name="image_aid" value="" />
</div>
</div>
</div>
@gdarko
Copy link
Author

gdarko commented Dec 5, 2020

Thanks for the contribution. The gist has been updated.

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