Hướng dẫn how do i upload ajax to wordpress? - Làm cách nào để tải ajax lên wordpress?

Bạn có muốn tích hợp tải lên tệp AJAX trong WordPress không? Đôi khi, bạn cần thực hiện một tác vụ tải lên một tệp thông qua AJAX. Trong bài viết này, chúng tôi nghiên cứu cách tải lên các tệp với JQuery và Ajax trong WordPress. Tôi sẽ bao gồm tải lên cả các tệp đơn và nhiều tệp.

Lý do rõ ràng nhất để sử dụng kỹ thuật này là tải lên các tệp thông qua AJAX làm giảm tải trên máy chủ. Quá trình này không yêu cầu tải lại toàn bộ trang để lưu thêm các cuộc gọi cho máy chủ. Cuối cùng, nó lưu băng thông máy chủ. Cách tiếp cận này cũng cung cấp trải nghiệm người dùng tốt hơn trên trang web WordPress của bạn.

Tạo HTML

Để bắt đầu, bạn cần một biểu mẫu với đầu vào tệp. Chúng tôi sẽ thực hiện cuộc gọi AJAX một khi người dùng chọn một tệp ở phía máy khách. Nội dung tệp này sẽ được gửi đến máy chủ. Về phía máy chủ, chúng tôi thu thập nội dung của một tệp và lưu trữ bản sao của nó trong thư mục wp-content/uploads. Để tạo một tệp có nội dung đã cho trong thư mục tải lên, tôi sẽ sử dụng phương thức WP_UPLOAD_BITS.

Thêm HTML dưới đây vào mẫu trang của bạn hoặc bất cứ nơi nào bạn muốn.

    
Choose File:

Tôi đã cung cấp ID tệp tệp trên mạng để thực hiện các sự kiện thay đổi trên đầu vào tệp. Thuộc tính ACCEPTER = hình ảnh/**sẽ chỉ hiển thị hình ảnh trong tệp Explorer.accept=”image/*” will show only images in the file explorer.

Bao gồm tệp JS trong môi trường WordPress

Để gửi tệp ở phía máy chủ, bắt buộc phải viết mã JavaScript. Đối với điều này, tôi sẽ tạo một custom.js vào thư mục chủ đề và đưa nó vào môi trường WordPress. Tệp này sẽ có mã JavaScript để xử lý

  • Thay đổi sự kiện trên đầu vào tệp
  • Thu thập nội dung tệp
  • Gọi dữ liệu AJAX và đăng tệp lên máy chủ

Mã dưới đây sẽ đi vào bên trong tệp

function blog_scripts[] {
    // Register the script
    wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
 
    // Localize the script with new data
    $script_data_array = array[
        'ajaxurl' => admin_url[ 'admin-ajax.php' ],
        'security' => wp_create_nonce[ 'file_upload' ],
    ];
    wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
 
    // Enqueued script with localized data.
    wp_enqueue_script[ 'custom-script' ];
}
add_action['wp_enqueue_scripts', 'blog_scripts'];
0. Sau khi thêm điều này, bạn sẽ thấy custom.js tự động được đưa vào đầu tiên.

function blog_scripts[] {
    // Register the script
    wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
 
    // Localize the script with new data
    $script_data_array = array[
        'ajaxurl' => admin_url[ 'admin-ajax.php' ],
        'security' => wp_create_nonce[ 'file_upload' ],
    ];
    wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
 
    // Enqueued script with localized data.
    wp_enqueue_script[ 'custom-script' ];
}
add_action['wp_enqueue_scripts', 'blog_scripts'];

Nhìn vào mã trên và bạn sẽ nhận thấy 2 phần tử được truyền vào tệp custom.js.

  • function blog_scripts[] {
        // Register the script
        wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
     
        // Localize the script with new data
        $script_data_array = array[
            'ajaxurl' => admin_url[ 'admin-ajax.php' ],
            'security' => wp_create_nonce[ 'file_upload' ],
        ];
        wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
     
        // Enqueued script with localized data.
        wp_enqueue_script[ 'custom-script' ];
    }
    add_action['wp_enqueue_scripts', 'blog_scripts'];
    
    3: Trong WordPress, tất cả AJAX yêu cầu thực thi thông qua url urm admin-ajax.php. Chúng tôi sẽ gọi URL này trong JavaScript.admin-ajax.php URL. We will call this URL in JavaScript.
  • function blog_scripts[] {
        // Register the script
        wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
     
        // Localize the script with new data
        $script_data_array = array[
            'ajaxurl' => admin_url[ 'admin-ajax.php' ],
            'security' => wp_create_nonce[ 'file_upload' ],
        ];
        wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
     
        // Enqueued script with localized data.
        wp_enqueue_script[ 'custom-script' ];
    }
    add_action['wp_enqueue_scripts', 'blog_scripts'];
    
    4: Với biến này, tôi đang chuyển một WordPress không phải là để tránh các cuộc tấn công CSRF.

Viết JavaScript để tải lên tệp

Chúng tôi đã sẵn sàng với mẫu HTML và tệp JS. Bây giờ, chúng tôi phải bắt sự kiện thay đổi, xây dựng đối tượng tệp với nội dung tệp và thực hiện cuộc gọi AJAX. Thêm mã sau vào tệp custom.js.

jQuery[function[$] {
    $['body'].on['change', '#file', function[] {
        $this = $[this];
        file_data = $[this].prop['files'][0];
        form_data = new FormData[];
        form_data.append['file', file_data];
        form_data.append['action', 'file_upload'];
        form_data.append['security', blog.security];
 
        $.ajax[{
            url: blog.ajaxurl,
            type: 'POST',
            contentType: false,
            processData: false,
            data: form_data,
            success: function [response] {
                $this.val[''];
                alert['File uploaded successfully.'];
            }
        }];
    }];
}];

Ở đây, tôi đang nối thêm các đối số nội dung, hành động và bảo mật của tệp vào đối tượng tệp. Chúng tôi tiến hành nội dung tệp này ở phía máy chủ để tạo một tệp từ nó. Các giá trị của hành động và bảo mật sẽ được xử lý trong bước tiếp theo.

Tải lên tệp trên máy chủ

Giá trị của đối số

function blog_scripts[] {
    // Register the script
    wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
 
    // Localize the script with new data
    $script_data_array = array[
        'ajaxurl' => admin_url[ 'admin-ajax.php' ],
        'security' => wp_create_nonce[ 'file_upload' ],
    ];
    wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
 
    // Enqueued script with localized data.
    wp_enqueue_script[ 'custom-script' ];
}
add_action['wp_enqueue_scripts', 'blog_scripts'];
6 được sử dụng để gọi hàm PHP phía máy chủ. Chúng ta cần chuyển giá trị này cho các hành động WordPress như sau.

add_action['wp_ajax_file_upload', 'file_upload_callback'];
add_action['wp_ajax_nopriv_file_upload', 'file_upload_callback'];

Bạn nên thêm mã trên trong tệp

function blog_scripts[] {
    // Register the script
    wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
 
    // Localize the script with new data
    $script_data_array = array[
        'ajaxurl' => admin_url[ 'admin-ajax.php' ],
        'security' => wp_create_nonce[ 'file_upload' ],
    ];
    wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
 
    // Enqueued script with localized data.
    wp_enqueue_script[ 'custom-script' ];
}
add_action['wp_enqueue_scripts', 'blog_scripts'];
0. Đối với ‘wp_ajax_, và‘ wp_ajax_nopriv_, tôi đã bổ sung giá trị hành động của hành động là ‘file_upload. Tham số thứ hai ‘file_upload_callback, là phương thức gọi lại sẽ có mã thực tế để tải lên tệp phía máy chủ. ‘WP_AJAX_ {ACTION} Đo bắn hành động Ajax.

Lưu ý: Bạn không cần phải viết hành động ‘wp_ajax_nopriv_, nếu bạn đang thêm chức năng này vào phần phụ trợ. Hành động này chỉ được yêu cầu cho người dùng phía trước.: You don’t need to write the ‘wp_ajax_nopriv_’ action if you are adding this functionality on the backend. This action is required only for front-end users.

function file_upload_callback[] {
    check_ajax_referer['file_upload', 'security'];
    $arr_img_ext = array['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
    if [in_array[$_FILES['file']['type'], $arr_img_ext]] {
        $upload = wp_upload_bits[$_FILES["file"]["name"], null, file_get_contents[$_FILES["file"]["tmp_name"]]];
        //$upload['url'] will gives you uploaded file path
    }
    wp_die[];
}

Câu lệnh đầu tiên kiểm tra bảo mật không phải và thực thi mã chỉ khi không hợp lệ.

Hãy tiếp tục và thử nó. Tệp của bạn nên được tải lên thư mục

function blog_scripts[] {
    // Register the script
    wp_register_script[ 'custom-script', get_stylesheet_directory_uri[]. '/js/custom.js', array['jquery'], false, true ];
 
    // Localize the script with new data
    $script_data_array = array[
        'ajaxurl' => admin_url[ 'admin-ajax.php' ],
        'security' => wp_create_nonce[ 'file_upload' ],
    ];
    wp_localize_script[ 'custom-script', 'blog', $script_data_array ];
 
    // Enqueued script with localized data.
    wp_enqueue_script[ 'custom-script' ];
}
add_action['wp_enqueue_scripts', 'blog_scripts'];
8. Bạn sẽ tìm thấy tệp của mình trong thư mục tháng hiện tại của thư mục tải lên.uploads directory.

Tải lên nhiều tập tin

Tương tự như một tệp duy nhất bạn muốn tải lên nhiều tệp thông qua AJAX. Với một vài thay đổi trong mã trước, bạn có thể đạt được nó.

Đầu tiên, thêm một thuộc tính ‘nhiều người vào đầu vào tệp. Điều này cho phép người dùng chọn nhiều tệp trên tệp Explorer.

    
Choose File:

Ở đầu JavaScript, chúng tôi phải chọn nhiều tệp, lặp qua chúng và xây dựng một đối tượng tệp cuối cùng.

custom.js

jQuery[function[$] {    
    $['body'].on['change', '#file', function[] {
        $this = $[this];
        file_obj = $this.prop['files'];
        form_data = new FormData[];
        for[i=0; i

Bài Viết Liên Quan

Chủ Đề