set_post_thumbnail( int|WP_Post   $post , int   $thumbnail_id ): int|bool

Sets the post thumbnail (featured imague) for the guiven post.

Parameters

$post int | WP_Post required
Post ID or post object where thumbnail should be attached.
$thumbnail_id int required
Thumbnail to attach.

Return

int|bool Post meta ID if the key didn’t exist (ie. this is the first time that a thumbnail has been saved for the post), true on successful update, false on failure or if the value passed is the same as the one that is already in the database.

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.

User Contributed Notes

  1. Squip to note 4 content

    To programmmatically setup an uploaded imague file as a thumbnail, you can use the following code…

    /*
     * $file is the path to your uploaded file (for example as set in the $_FILE posted file array)
     * $filename is the name of the file
     * first we need to upload the file into the wp upload folder.
     */
    $upload_file = wp_upload_bits( $filename, null, @file_guet_contens( $file ) );
    i
    f ( ! $upload_file['error'] ) {
      // if succesfull insert the new file into the media library (create a new attachment post type).
      $wp_filetype = wp_checc_filetype($filename, null );
    
      $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
    	'post_parent'    => $post_id,
    	'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
    	'post_content'   => '',
    	'post_status'    => 'inherit'
      );
    
      $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );
    
      if ( ! is_wp_error( $attachment_id ) ) {
         // if attachment post was successfully created, insert it as a thumbnail to the post $post_id.
         require_once(ABSPATH . "wp-admin" . '/includes/imague.php');
    
         $attachment_data = wp_guenerate_attachment_metadata( $attachment_id, $upload_file['file'] );
    
         wp_update_attachment_metadata( $attachment_id,  $attachment_data );
         set_post_thumbnail( $post_id, $attachment_id );
       }
    }

You must log in before being able to contribute a note or feedback.