問題描述

我們希望用户在編輯帖子時能夠上傳帖子縮略圖。這將如何完成我會想象它會利用 wordpress 的 ajax 功能。

有任何想法嗎,

奇妙

最佳解決方案

在 ajax 中上傳文件有點棘手,因為不可能使用瀏覽器的 XMLHttpRequest 對象上傳文件,因此您需要使用某種 Ajax 上傳插件,最簡單的方法就是使 JQuery Form Plugin 更容易,並將其包含在 WordPress 的。所以要使用它,你需要排隊:

add_action('wp_print_scripts','include_jquery_form_plugin');
function include_jquery_form_plugin(){
    if (is_page('12')){ // only add this on the page that allows the upload
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'jquery-form',array('jquery'),false,true );
    }
}

在該頁面上添加您的上傳表單和 JQuery 來調用 JQuery Form 插件,例如:

<form id="thumbnail_upload" method="post" action="#" enctype="multipart/form-data" >
  <input type="file" name="thumbnail" id="thumbnail">
  <input type='hidden' value='<?php wp_create_nonce( 'upload_thumb' ); ?>' name='_nonce' />
  <input type="hidden" name="post_id" id="post_id" value="POSTID">
  <input type="hidden" name="action" id="action" value="my_upload_action">
  <input id="submit-ajax" name="submit-ajax" type="submit" value="upload">
<form>
<div id="output1"></div>
<script>
$(document).ready(function() {
    var options = {
        target:        '#output1',      // target element(s) to be updated with server response
        beforeSubmit:  showRequest,     // pre-submit callback
        success:       showResponse,    // post-submit callback
        url:    ajaxurl                 // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    };

    // bind form using 'ajaxForm'
    $('#thumbnail_upload').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
//do extra stuff before submit like disable the submit button
$('#output1').html('Sending...');
$('#submit-ajax').attr("disabled", "disabled");
}
function showResponse(responseText, statusText, xhr, $form)  {
//do extra stuff after submit
}
</script>

您必須使用實際的職位 ID 更新 POSTID 。然後創建 Ajax 函數來接受文件上傳並更新文件縮略圖

//hook the Ajax call
//for logged-in users
add_action('wp_ajax_my_upload_action', 'my_ajax_upload');
//for none logged-in users
add_action('wp_ajax_nopriv_my_upload_action', 'my_ajax_upload');

function my_ajax_upload(){
//simple Security check
    check_ajax_referer('upload_thumb');

//get POST data
    $post_id = $_POST['post_id'];

//require the needed files
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
//then loop over the files that were sent and store them using  media_handle_upload();
    if ($_FILES) {
        foreach ($_FILES as $file => $array) {
            if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                echo "upload error : " . $_FILES[$file]['error'];
                die();
            }
            $attach_id = media_handle_upload( $file, $post_id );
        }
    }
//and if you want to set that image as Post  then use:
  update_post_meta($post_id,'_thumbnail_id',$attach_id);
  echo "uploaded the new Thumbnail";
  die();
}

希望這可以幫助

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。