![](/img/trans.png)
[英]WordPress: Frontend form to create custom type post with featured image
[英]issue in uploading featured in custom post type from frontend
<div class="modal-body">
<form method="POST" action="">
<input type="file" name="featured_img"><br/>
<input type="submit" name="imgupdate" class="btn btn-info btn-lg">
<button type="button" class="btn btn-info btn-lg" data-dismiss="modal">Cancel</button>
</form>
</div>
<?php
global $wpdb;
$update_id = get_the_ID();
// Update featured image
$uploaddir = wp_upload_dir();
$file = $_FILES['featured_img'];
$uploadfile = $uploaddir['path'] . '/' . basename($file['name']);
move_uploaded_file($file['tmp_name'], $uploadfile);
$filename = basename($uploadfile);
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'menu_order' => $_i + 1000
);
$update_img = wp_insert_attachment($attachment, $uploadfile);
if (isset($_POST['imgupdate'])) {
if (($_FILES['featured_img']['name'] == true)) {
update_post_meta($update_id, '_thumbnail_id', $update_img);
}
}
?>
我想從前端編輯特色圖片,我想通過使用此代碼來實現這一點,但是它不起作用。它無法更新圖片。 有什么幫助嗎? 我在哪里遇到問題。 此代碼在其他頁面上工作正常。 但是我想在模型中彈出這個。 這在彈出窗口中不起作用。 有什么幫助嗎?
提前致謝。
您可以添加這樣的代碼,它對我有用。
希望這也對您有用。
if ($_FILES) {
array_reverse($_FILES);
if ($_FILES['file_featured_image']) {
$i = 0; //this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0)
$set_feature = 1; //if $i ==0 then we are dealing with the first post
else
$set_feature = 0; //if $i!=0 we are not dealing with the first post
insert_featured_image_for_property($file, $property_id, $set_feature);
$i++; //count posts
}
}
}
在functions.php中添加一個函數
function insert_featured_image_for_property($file_handler, $property_id, $setthumb = 'false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) {
return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload($file_handler, $property_id);
//set post thumbnail if setthumb is 1
if ($setthumb == 1)
update_post_meta($property_id, '_thumbnail_id', $attach_id);
return $attach_id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.