Upload hình ảnh avatar tùy chỉnh trong WordPress

Đoạn code ví dụ upload hình ảnh tùy chỉnh lên dùng làm avatar cho người dùng WordPress:

// Dashboard profile
$(".change-avatar-form").on("click", "a", function (e) {
    e.preventDefault();
    let element = $(this),
        form = element.parent(),
        input = form.find("input"),
        avatar = form.find("img");

    input.on("change", function () {
        let files = this.files;

        if (files.length) {
            let file = files[0];

            if (file) {
                // Show loading when choose image
                avatar.attr("data-old-src", avatar.attr("src"));
                avatar.attr("src", BF_FRONTEND.spinnerUrl);

                let _URL = window.URL || window.webkitURL,
                    imageWidth = 0,
                    imageHeight = 0;

                let img = new Image();

                img.onload = function () {
                    imageWidth = this.width;
                    imageHeight = this.height;
                };

                img.src = _URL.createObjectURL(file);

                let avatarWarning = false;

                setTimeout(function () {
                    if (imageWidth !== imageHeight || imageWidth > 128) {
                        if (!avatarWarning) {
                            avatarWarning = true;
                            alert("Avatar must be a square and image size smaller than 128x128 pixels!");
                            avatar.attr("src", avatar.attr("data-old-src"));
                            return false;
                        }

                        return;
                    }

                    let Upload = function (file) {
                        this.file = file;
                    };

                    Upload.prototype.getType = function () {
                        return this.file.type;
                    };

                    Upload.prototype.getSize = function () {
                        return this.file.size;
                    };

                    Upload.prototype.getName = function () {
                        return this.file.name;
                    };

                    Upload.prototype.doUpload = function () {
                        let that = this;
                        let formData = new FormData();

                        // add assoc key values, this will be posts values
                        formData.append("file", this.file);
                        formData.append("upload_file", true);
                        formData.append("user_id", element.attr("data-user-id"));

                        $.ajax({
                            type: "POST",
                            url: BF_FRONTEND.ajaxUrl + "?action=hocwp_pxf_upload_avatar",
                            xhr: function () {
                                let myXhr = $.ajaxSettings.xhr();

                                if (myXhr.upload) {
                                    myXhr.upload.addEventListener("progress", that.progressHandling, false);
                                }

                                return myXhr;
                            },
                            success: function (response) {
                                if (response.success) {
                                    avatar.attr("src", response.data.url);
                                } else {
                                    avatar.attr("src", avatar.attr("data-old-src"));
                                }
                            },
                            error: function (error) {
                                // handle error
                            },
                            async: true,
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            timeout: 60000
                        });
                    };

                    Upload.prototype.progressHandling = function (event) {
                        let percent = 0;
                        let position = event.loaded || event.position;
                        let total = event.total;

                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }
                    };

                    let upload = new Upload(file);

                    // maby check size or type here with upload.getSize() and upload.getType()

                    // execute upload
                    upload.doUpload();
                }, 1000);
            }
        }
    });

    input.trigger("click");
});

Đoạn HTML hiển thị hình ảnh avatar:

<div class="fes-el html html_1519802597 text-center my-4">
    <div class="fes-fields">
        <div class="zf-user-avatar-field">
            <div class="change-avatar-form">
                <a href="javascript:" data-user-id="1">
                    <img decoding="async" class="avatar"
                         src="https://localhost/ldcuong/wp-content/uploads/2024/11/dailydeal-75x75.png" alt="" width="96"
                         height="96">
                </a>
                <input type="file" name="avatar_id" style="display: none" accept=".jpg, .png">
            </div>
        </div>
    </div>
</div>

Đoạn code xử lý AJAX khi người dùng chọn tải hình ảnh avatar lên:

function hocwp_pxf_upload_avatar_ajax_callback() {
    $data    = array();
    $user_id = $_POST['user_id'] ?? '';

    if ( BigFont_Object()->is_positive_number( $user_id ) ) {
        $file = $_FILES['file'] ?? '';

        if ( isset( $file['name'] ) ) {
            $upload = Pixelify()->upload_file( basename( $file['name'] ), $file['tmp_name'] );

            if ( isset( $upload['id'] ) ) {
                $data['url'] = wp_get_attachment_image_url( $upload['id'] );
                update_user_meta( $user_id, 'avatar_id', $upload['id'] );
                wp_send_json_success( $data );
            }
        }
    }

    wp_send_json_error( $data );
}

add_action( 'wp_ajax_hocwp_pxf_upload_avatar', 'hocwp_pxf_upload_avatar_ajax_callback' );

Filter để hiển thị hình ảnh avatar từ ảnh tùy chỉnh được tải lên bởi người dùng:

function hocwp_pxf_pre_get_avatar_filter( $avatar, $id_or_email, $args ) {
    $user = HP()->get_user( $id_or_email );

    if ( $user instanceof WP_User ) {
        $avatar_id = get_user_meta( $user->ID, 'avatar_id', true );

        if ( HP()->is_positive_number( $avatar_id ) && file_exists( get_attached_file( $avatar_id ) ) ) {
            $avatar = '<img class="avatar" src="' . wp_get_attachment_image_url( $avatar_id, array(
                    75,
                    75,
                    true
                ) ) . '" alt="" width="' . $args['width'] . '" height="' . $args['height'] . '">';
        }
    }

    return $avatar;
}

add_filter( 'pre_get_avatar', 'hocwp_pxf_pre_get_avatar_filter', 10, 3 );

 

5/5 - (1 bình chọn)

Không có bình luận.

Bạn có thể trở thành người đầu tiên để lại bình luận.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *