Im trying to upload an external image and set it as a featured image via php
The code im using is as follows,
$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)
It uploads the image to the media but doesn’t set as the featured image, however i think the problem is in the image upload, the attachment screen in the ‘media’ looks as follow
http://cl.ly/image/0z2k1b1d0m1J
Which seems to suggest some information hasnt come through correctly as theres no thumbnail, name or type.
All help much appreciated!
Thanks
I would comment, but I’m not allowed yet.
1) Are you doing this from the back-end or front-end? You may need a nonce key.
2) On
set_post_thumbnail
, does$newId = $post->ID
? That may be why it’s not attaching as the featured image.3) Your filename is not preserving the extension/
$photo_name
is not defined in the code. You may be better off with wp_handle_upload.