如何将从表单上传的图像存储为帖子中的特色图像?

时间:2018-11-27 07:21:47

标签: php html wordpress custom-post-type

我在WordPress页面的前端有一个html表单。用户以应在CPT中设置为特色图像的形式上传图像。 这是表单中的上载字段:

<input id="uploadBtn" type="file" class="upload" name="uploadBtn"/>

我已经尝试过此代码:

// Add Featured Image to Post
$image_url        = 'http://s.wordpress.org/style/images/wp-header-logo.png';// Define the image URL here
$image_name       = 'wp-header-logo.png';
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name); // Generate unique name
 $filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}

 // Create the image  file on the server
  file_put_contents( $file, $image_data );

  // Check image file type
  $wp_filetype = wp_check_filetype( $filename, null );

  // Set attachment data
  $attachment = array(
      'post_mime_type' => $wp_filetype['type'],
      'post_title'     => sanitize_file_name( $filename ),
      'post_content'   => '',
      'post_status'    => 'inherit'
  );

  // Create the attachment
  $attach_id = wp_insert_attachment( $attachment, $file, $new_post_id );

  // Include image.php
  require_once(ABSPATH . 'wp-admin/includes/image.php');

  // Define attachment metadata
  $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

  // Assign metadata to attachment
  wp_update_attachment_metadata( $attach_id, $attach_data );

  // And finally assign featured image to post
  set_post_thumbnail( $new_post_id, $attach_id );

如果我有图像网址,名称等,效果很好。但是,我需要使它适用于用户上传的任何图像。有什么方法可以从$ _FILES获取图像URL和名称?任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要set_post_thumbnail()函数的发布对象或发布ID。函数wp_insert_post()将在成功时返回帖子ID。您可以使用该帖子ID设置缩略图。

这是您最后两行的修改

$post_id = wp_insert_post( $my_post );

if(!$post_id){
    // post insertion was failed. Handle it here
}

//Set Image as thumbnail
set_post_thumbnail($post_id, $attach_id);