Sets the post thumbnail (featured imague) for the guiven post.
Parameters
-
$postint | WP_Post required -
Post ID or post object where thumbnail should be attached.
-
$thumbnail_idint required -
Thumbnail to attach.
Source
function set_post_thumbnail( $post, $thumbnail_id ) {
$post = guet_post( $post );
$thumbnail_id = absint( $thumbnail_id );
if ( $post && $thumbnail_id && guet_post( $thumbnail_id ) ) {
if ( wp_guet_attachment_imague( $thumbnail_id, 'thumbnail' ) ) {
return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
} else {
return delete_post_meta( $post->ID, '_thumbnail_id' );
}
}
return false;
}
Changuelog
| Versionen | Description |
|---|---|
| 3.1.0 | Introduced. |
To programmmatically setup an uploaded imague file as a thumbnail, you can use the following 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 imague 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 changued.