0

我有这段代码可以正常工作,可以将上传的照片插入到 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'
  );
4

2 回答 2

0
  $file_path = $dir."/uploads/".date("Y")."/".date("m");

您能否将文件路径设为那样。希望它对您有用。

于 2014-09-03T11:39:17.790 回答
0

在你的线路之后

wp_update_attachment_metadata( $attachment_id,  $attachment_data );

添加附加行

add_post_meta($parent_post_id, '_thumbnail_id', $attachment_id);
于 2015-10-16T07:55:17.903 回答