I want to upload an image and set it as a featured image in a post.
What i tried was this:
$image_id = media_sideload_image($image_url, $post_id, $post_id);
update_post_meta($post_id, '_thumbnail_id', $image_id);
But media_sideload_image()
is not returning the image_id
, but the render html image.
How can I get the image_id
?
Here is an example of how to bypass this limitation using actions/hooks:
The idea is that when
media_sideload_image
is ran, it:attachment
)Your issue is that it does not provide the newly created attachment posts ID.
But, when an attachment is created, an action is fired containing its ID. We can hook into this before we create the attachment, and save the featured thumbnail with the post ID it gave us, then unhook afterwards.
There is no need for the older solutions anymore.
You can get The ID with a fourth paramenter($return) set to ‘id’
https://codex.wordpress.org/Function_Reference/media_sideload_image
I’ve build a function to get the ID from DB, searching by URL.
You can get URL (insted of html code) with a fourth paramenter set to
'src'
Codex: media_sideload_image()
@Tom J Nowell’s answer is spot on. I found another alternative (using different functions) explained here but I like this one more.
In my case I have an array of $posts with all the posts I want to insert and a separate $media (same $nid keys as $posts) with the media. My code is the same solution as Tom’s but refactored to use an anonymous function:
In my case I assume the 1st item in each $media[$nid] shuold be the featured image of its post.
WordPress shouold definitely change media_sideload_image() so it returns the $id . In fact the function has it at hand, see the source here. In fact there’s a track ticket for this and they even have patches to apply this to your core in the mean time if you want.
I was looking for a solution and decided to look at the code for
media_sideload_image()
which was very straightforward. It usesmedia_handle_sideload()
which gives us the attachmentid
.I modified it to return the attachment
id
instead of the html source of the image, and even added a way to send it new filename.You can use the media_handle_sideload instead of media_sideload_image.Also if you are using this function in functions.php don’t forgot to add below three lines.