自动将缩略图添加到帖子

时间:2012-05-12 作者:Damian Czapiewski

我有以下代码。

 $postData = array(
   \'post_category\' => array(get_category_id("website")),
   \'post_content\' => \'My website about cars.\',
   \'post_title\' => \'my little cars\',
   \'post_type\' => \'post\',
   \'post_status\' => \'publish\',
   \'tags_input\' => \'cars, hobbies\'
  );
  $pID = wp_insert_post($postData);
  update_post_meta($pID, "language", "English");
  update_post_meta($pID, "author", "John");
以及如何添加帖子缩略图?下面编写的代码不正确。

 $filename = "http://damianc.pl/th.jpg";
 $wp_filetype = wp_check_filetype(basename($filename), null);
 $wp_upload_dir = wp_upload_dir();
 $attachment = array(
  \'guid\' => $wp_upload_dir[\'baseurl\'] . _wp_relative_upload_path( $filename ), 
  \'post_mime_type\' => $wp_filetype[\'type\'],
  \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename)),
  \'post_content\' => \'\',
  \'post_status\' => \'inherit\'
 );
 $attach_id = wp_insert_attachment( $attachment, $filename, $pID );
 require_once(ABSPATH . \'wp-admin/includes/image.php\');
 $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
 wp_update_attachment_metadata( $attach_id, $attach_data );
图像路径良好。我不知道。

1 个回复
最合适的回答,由SO网友:Eugene Manuilov 整理而成

This should work:

$wp_upload_dir = wp_upload_dir();

$fileurl = "http://damianc.pl/th.jpg";
$filename = $upload_dir[\'path\'] . DIRECTORY_SEPARATOR . basename( $fileurl );

if ( file_put_contents( $filename, file_get_contents( $fileurl ) ) ) {
    require_once(ABSPATH . \'wp-admin/includes/image.php\');

    $wp_filetype = wp_check_filetype(basename($filename), null);
    $attachment = array(
      \'post_mime_type\' => $wp_filetype[\'type\'],
      \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename)),
      \'post_content\' => \'\',
      \'post_status\' => \'inherit\'
    );
    $attach_id = wp_insert_attachment( $attachment, $filename, $pID );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    update_post_meta( $pID, \'_thumbnail_id\', $attach_id );
}
结束

相关推荐

Double thumbnails?

是否可以使用缩略图机制两次?我发现缩略图API非常有用,它允许用户在其中放置自己的图形,以便我可以轻松控制大小和位置。他们所要做的就是记住点击特色图片。我想在我的页面上有两个这样的机制,你知道我该怎么做吗?最好是手工编码。