set_post_thumbnail( int|WP_Post $post, int $thumbnail_id )
Sets the post thumbnail (featured image) for the given post.
Parameters Parameters
- $post
-
(int|WP_Post) (Required) Post ID or post object where thumbnail should be attached.
- $thumbnail_id
-
(int) (Required) Thumbnail to attach.
Return Return
(int|bool) True on success, false on failure.
Source Source
File: wp-includes/post.php
function set_post_thumbnail( $post, $thumbnail_id ) { $post = get_post( $post ); $thumbnail_id = absint( $thumbnail_id ); if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) { if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) { return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); } else { return delete_post_meta( $post->ID, '_thumbnail_id' ); } } return false; }
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
3.1.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
To programmatically setup an uploaded image file as a thumbnail, you can use the following code…
Expand full source codeCollapse full source code
The return value is not “True on success”
On success, the return value is the new meta field ID returned by the update_post_meta function or TRUE if delete_post_meta is successful.
This method will return false the second time you run it. If the featured image is already set to the attachment ID you provide, the method returns false because `update_post_meta` returns false when the value would not be changed.