Skip to content

Instantly share code, notes, and snippets.

@cgdmohamed
Last active July 19, 2023 10:04
Show Gist options
  • Save cgdmohamed/63b9811362d0fa3be4627925da45d7f9 to your computer and use it in GitHub Desktop.
Save cgdmohamed/63b9811362d0fa3be4627925da45d7f9 to your computer and use it in GitHub Desktop.
AJAX Uploading and removing profile picture woocommerce
<?php
/**
* Author: https://mo.hamed.dev
* This file handles uploading and removing custom profile pic with AJAX
* Please note, you have to add removing image AJAX request
*/
add_action('wp_enqueue_scripts', 'moodev_enqueue_scripts');
function moodev_enqueue_scripts()
{
// Enqueue your custom JavaScript file
wp_enqueue_script('moodev-custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true);
// Localize the script with your AJAX URL
wp_localize_script('moodev-custom-js', 'moodevAjax', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'profilePicNonce' => wp_create_nonce('moodev_profile_picture_upload'),
'removePicNonce' => wp_create_nonce('moodev_remove_profile_picture')
));
}
add_action('woocommerce_before_edit_account_form', 'moodev_cpp_form');
function moodev_cpp_form($atts, $content = null)
{
ob_start();
?>
<div style="margin-bottom: 15px;">
<?php echo get_avatar(get_current_user_id(), 256, null, null, array('class' => 'rounded-circle')); ?>
<form id="profile-picture-form" enctype="multipart/form-data" method="POST">
<input type="file" id="profile-pic-input" name="profile_pic" accept="image/*" style="display: none;" />
<label for="profile-pic-input" class="btn btn-primary btn-lg text-light">
<?php esc_html_e('Choose Image', 'moodev'); ?>
</label>
<button type="button" id="upload-btn" class="btn btn-primary btn-lg text-light" disabled>
<?php esc_html_e('Upload', 'moodev'); ?>
</button>
<input type="hidden" name="action" value="moodev_handle_profile_picture_upload" />
<?php wp_nonce_field('moodev_profile_picture_upload', 'moodev_profile_picture_nonce', true, false); ?>
</form>
<?php
// Display remove picture option if user has a profile picture
$user_id = get_current_user_id();
$profile_picture_id = get_user_meta($user_id, 'profile_pic', true);
if (!empty($profile_picture_id)) :
?>
<br>
<form>
<button id="remove-profile-pic-btn" class="btn bg-primary btn-lg text-primary bg-opacity-25 bg-opacity-10">
<?php esc_html_e('Remove Profile Picture', 'moodev'); ?>
</button>
</form>
<?php endif; ?>
</div>
<?php
echo ob_get_clean();
}
add_action('wp_ajax_moodev_handle_profile_picture_upload', 'moodev_handle_profile_picture_upload');
add_action('wp_ajax_nopriv_moodev_handle_profile_picture_upload', 'moodev_handle_profile_picture_upload');
if (!function_exists('moodev_handle_profile_picture_upload')) {
function moodev_handle_profile_picture_upload()
{
if (!isset($_POST['moodev_profile_picture_nonce']) || !wp_verify_nonce($_POST['moodev_profile_picture_nonce'], 'moodev_profile_picture_upload')) {
wp_send_json_error('Invalid nonce.');
}
if (!current_user_can('edit_user', get_current_user_id())) {
wp_send_json_error('Insufficient permissions.');
}
if (!isset($_FILES['profile_pic']) || empty($_FILES['profile_pic']['name'])) {
wp_send_json_error('No image uploaded.');
}
$picture_id = moodev_upload_picture($_FILES['profile_pic']);
if (!$picture_id) {
wp_send_json_error('Failed to upload image.');
}
$user_id = get_current_user_id();
moodev_save_profile_pic($picture_id, $user_id);
wp_send_json_success('Image uploaded successfully.');
}
}
function moodev_upload_picture($foto)
{
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name already exists
$profilepicture = $foto;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type($profilepicture['tmp_name']);
if (empty($profilepicture)) {
wp_send_json_error('File is not selected.');
}
if ($profilepicture['error']) {
wp_send_json_error($profilepicture['error']);
}
if ($profilepicture['size'] > wp_max_upload_size()) {
wp_send_json_error('The uploaded file is too large.');
}
if (!in_array($new_file_mime, get_allowed_mime_types())) {
wp_send_json_error('WordPress doesn\'t allow this type of upload.');
}
while (file_exists($new_file_path)) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
if (move_uploaded_file($profilepicture['tmp_name'], $new_file_path)) {
$upload_id = wp_insert_attachment(
array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace('/\.[^.]+$/', '', $profilepicture['name']),
'post_content' => '',
'post_status' => 'inherit'
),
$new_file_path
);
require_once(ABSPATH . 'wp-admin/includes/image.php');
wp_update_attachment_metadata($upload_id, wp_generate_attachment_metadata($upload_id, $new_file_path));
return $upload_id;
} else {
wp_send_json_error('Failed to move the uploaded file.');
}
}
function moodev_save_profile_pic($picture_id, $user_id)
{
update_user_meta($user_id, 'profile_pic', $picture_id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment