我试图上传一个外部图像,并通过php将其设置为特色图像
我使用的代码如下,
$photo = new WP_Http();
$photo = $photo->request( $article->largeURL );
$attachment = wp_upload_bits( $photo_name . '.jpg', null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
$filetype = wp_check_filetype( basename( $attachment['file'] ), null );
$postinfo = array(
'post_mime_type' => $filetype['type'],
'post_title' => $article->heading . ' ',
'post_content' => '',
'post_status' => 'inherit',
);
$filename = $attachment['file'];
$attach_id = wp_insert_attachment( $postinfo, $filename, $newId );
if( !function_exists( 'wp_generate_attachment_data' ) )
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 );
set_post_thumbnail($newId,$attach_id)
它将图像上载到媒体,但未设置为特色图像,但我认为问题出在图像上载中,“媒体”中的附件屏幕如下所示
http://cl.ly/image/0z2k1b1d0m1J
这似乎表明,一些信息没有通过正确的,因为没有缩略图,名称或类型。
感谢大家的帮助!
谢谢
最佳答案
我想发表评论,但现在还不允许。
1)您是从后端还是前端执行此操作?您可能需要一个nonce key。
2)打开set_post_thumbnail
,是否$newId = $post->ID
?这可能就是为什么它没有附加为特色图像的原因。
3)您的文件名没有保留代码中未定义的扩展名/$photo_name
。wp_handle_upload可能会让你过得更好。