###### tags: `wordpress` `ajax` `前台建立文章` # 🔍如何使用前端表單在後台建立文章?👊 --- ## 1. 前端表單基本程式碼樣貌與執行方式: # index.php ```php= <form id="postPost" method="post" action="" enctype="multipart/form-data"> <input type="text" name="title"> <textarea name="content"></textarea> <input id="files" type="file" name="thumbnail" accept="image/png, image/gif, image/jpeg"> <input id="pdf" type="file" name="thumbnail" accept=".pdf"> <input type="submit" name="submit"> </form> ``` 💬說明:基本表單結構 # JavaScript.js ```javascript= jQuery(function ($) { // get post 測試 // 監聽 let postName = document.querySelector("[name='title']"); let postContent = document.querySelector("[name='content']"); let postThumbnail = document.querySelector("[name='thumbnail']"); let nameValue = ""; let contentValue = ""; postName.addEventListener("change", (e) => { nameValue = postName.value; }); postContent.addEventListener("change", (e) => { contentValue = postContent.value; }); // 點擊 submit 時,建立formData並將需要 ajax 的資料附加上去 $("#postPost").submit(function (event) { //console.log(postName); event.preventDefault(); var formData = new FormData(); // set_posts 為後端 funtions.php 執行的 function 名稱 formData.append("action", "set_posts"); formData.append("name", nameValue); formData.append("content", contentValue); formData.append("file", document.getElementById("files").files[0]); formData.append("pdf", document.getElementById("pdf").files[0]); //console.log(formData); // 將資料藉由 ajax 送去後端 $.ajax({ type: "POST", url: DHHU_vars.ajaxurl, // url:"https://www.goh.org.tw/gohadmin/admin-ajax.php", data: formData, // dataType: "json", processData: false, contentType: false, success: function (res) { //console.log(res); if (res.error) { console.log("錯誤"); } else { console.log("正確"); } }, }); }); // jQuery結尾 }); ``` 💬說明:使用 ajax 將表格資料傳送至後端處理 # funtions.php ```php= <?php // ajax add_action('wp_ajax_set_posts', 'set_posts'); add_action('wp_ajax_nopriv_set_posts', 'set_posts'); // 執行 function set_posts() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; // 前端獲取資料 $post_name = $_POST['name']; $post_content = $_POST['content']; // error_log(print_r($post_name, 1)); // error_log(print_r($post_content, 1)); // 寫入文章 $new_post = array( 'post_title' => $post_name, 'post_type' => 'post', 'post_staus' => 'draft', 'post_content' => $post_content, 'post_excerpt' => '', 'post_category' => array(21),//加入分類=>arry(分類ID) 'tax_input' => array( "post_tag" => 'tag test',//加入標籤=>tag 名稱 ), ); // 建立與抓取文章 ID $postID = wp_insert_post($new_post); // 圖片添加程式碼 if (!empty($_FILES['file'])) { // wp_die('No files selected.'); $upload = wp_handle_upload( $_FILES['file'], array('test_form' => false) ); // 上傳的圖片添加到 WordPress 媒體庫 $attachment_id = wp_insert_attachment( array( 'guid' => $upload['url'], 'post_mime_type' => $upload['type'], 'post_title' => basename($upload['file']), 'post_content' => '', 'post_status' => 'inherit', ), $upload['file'] ); if (is_wp_error($attachment_id) || !$attachment_id) { wp_die('Upload error.'); } // 更新元數據,重新生成圖像大小 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata($attachment_id, $upload['file']) ); // 重新定向上傳文件 wp_safe_redirect($upload['url']); // 設定特色圖片 // set_post_thumbnail(文章 ID, 媒體 ID); set_post_thumbnail($postID, $attachment_id); // exit; } // PDF 添加程式碼 if (!empty($_FILES['pdf'])) { $upload_pdf = wp_handle_upload( $_FILES['pdf'], array('test_form' => false) ); // 上傳的 PDF 添加到 WordPress 媒體庫 $attachment_id_pdf = wp_insert_attachment( array( 'guid' => $upload_pdf['url'], 'post_mime_type' => $upload_pdf['type'], 'post_title' => basename($upload_pdf['file']), 'post_content' => '', 'post_status' => 'inherit', ), $upload_pdf['file'] ); if (is_wp_error($attachment_id_pdf) || !$attachment_id_pdf) { wp_die('Upload error.'); } wp_update_attachment_metadata( $attachment_id_pdf, wp_generate_attachment_metadata($attachment_id_pdf, $upload_pdf['file']) ); // 上傳 ACF 欄位資料 // 後台需開設好 ACF 檔案欄位 // update_field(欄位名稱, 上傳資料, 文章 ID); update_field('pdf', $attachment_id_pdf, $postID); wp_safe_redirect($upload_pdf['url']); } update_field('test_1', $post_content, $postID); // 建立 ajax 回傳檔案內容 $array_result = array( 'data' => 'your data', 'message' => 'your message' ); wp_send_json($array_result); wp_die(); }; ``` 💬說明:functions.php 將收到資料後在後台建立文章與特色圖片,並將 PDF 檔案附加上已開設好的 ACF 檔案欄位。