On this page
set_post_thumbnail( int|WP_Post $post, int $thumbnail_id ): int|bool
Sets the post thumbnail (featured image) for the given post.
Parameters
$postint|WP_Post Required-
Post ID or post object where thumbnail should be attached.
$thumbnail_idint Required-
Thumbnail to attach.
Return
int|bool True on success, false on failure.
Source
File: wp-includes/post.php. View all references
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;
}
Related
Uses
| Uses | Description |
|---|---|
| update_post_meta() wp-includes/post.php | Updates a post meta field based on the given post ID. |
| wp_get_attachment_image() wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| delete_post_meta() wp-includes/post.php | Deletes a post meta field for the given post ID. |
| absint() wp-includes/functions.php | Converts a value to non-negative integer. |
| get_post() wp-includes/post.php | Retrieves post data given a post ID or post object. |
Used By
| Used By | Description |
|---|---|
| WP_REST_Posts_Controller::handle_featured_media() wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the featured media based on a request param. |
| wp_ajax_set_attachment_thumbnail() wp-admin/includes/ajax-actions.php | Ajax handler for setting the featured image for an attachment. |
| wp_ajax_set_post_thumbnail() wp-admin/includes/ajax-actions.php | Ajax handler for setting the featured image. |
| wp_insert_post() wp-includes/post.php | Inserts or update a post. |
| wp_xmlrpc_server::mw_editPost() wp-includes/class-wp-xmlrpc-server.php | Edit a post. |
| wp_xmlrpc_server::mw_newPost() wp-includes/class-wp-xmlrpc-server.php | Create a new post. |
| wp_xmlrpc_server::_insert_post() wp-includes/class-wp-xmlrpc-server.php | Helper method for wp_newPost() and wp_editPost(), containing shared logic. |
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |
© 2003–2022 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/set_post_thumbnail