从上端自定义帖子类型中上传的问题

时间:2017-10-10 08:38:45

标签: php mysql wordpress

    <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);
        }
    }

?>

我想从前端编辑精选图像我想通过使用此代码来实现这一点,但它无法正常工作。它不会更新图像。任何帮助?我遇到问题的地方。此代码在其他页面上正常工作。但我想在模型中弹出这个。这不适用于弹出窗口。有什么帮助吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

你可以添加这样的代码,它对我有用。

希望这对你也有用。

 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;
}