【问题标题】:set featured image after upload wordpress上传wordpress后设置特色图片
【发布时间】:2014-09-03 09:20:17
【问题描述】:

我有这段代码可以正常工作,可以将上传的照片插入到 wordpress 的库中,并成功创建帖子

但是将上传的照片设置为帖子上的特色图片不起作用

注意:我使用自定义帖子类型。

我在 stackoverflow 网络上尝试了很多解决方案,但都没有成功

$dir = plugin_dir_path( __FILE__ );
   $file_path = $dir."/uploads/";
    $text = $_POST['text'];
    $user = $_POST['usr'];
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path);


$file = $file_path;
$filename = basename($file);

$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent' => $parent_post_id,
        'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
    if (!is_wp_error($attachment_id)) {
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
        wp_update_attachment_metadata( $attachment_id,  $attachment_data );
    }
}

unlink($file_path);

$user = get_userdatabylogin($_POST['usr']);
$user_ID = $user->ID; // prints the id of the user

global $user_ID;

$new_post = array(
'post_title' => 'My New Post',
'post_content' => $_POST['text'],
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'taken_photos',
'post_category' => array(0)
);
$pid = wp_insert_post($new_post);

  update_post_meta($pid, '_thumbnail_id', $attachment_id);

  $attachment_data = array(
    'ID' => $attachment_id,
    'post_excerpt' => 'TITLE'
  );

【问题讨论】:

    标签: php wordpress custom-post-type dynamic-featured-image


    【解决方案1】:
      $file_path = $dir."/uploads/".date("Y")."/".date("m");
    

    你能把文件路径改成那样吗。希望它对你有用。

    【讨论】:

    • $file_path 与此无关,此文件路径也是临时的,如果您仔细查看代码,您会看到我在将其插入 wordpress 媒体后删除了此文件图书馆
    【解决方案2】:

    在你的行之后

    wp_update_attachment_metadata( $attachment_id,  $attachment_data );
    

    添加额外的行

    add_post_meta($parent_post_id, '_thumbnail_id', $attachment_id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 2014-11-22
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2013-09-17
      相关资源
      最近更新 更多