set_post_thumbnail

Set a post thumbnail.

Description

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

Returns (int|bool)

True on success, false on failure.

Parameters (2)

0. $post (int|WP_Post)
Post ID or post object where thumbnail should be attached.
1. $thumbnail_id (int)
Thumbnail to attach.

Usage

  1. if ( !function_exists( 'set_post_thumbnail' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Post ID or post object where thumbnail should be attached. 
  5. $post = null; 
  6.  
  7. // Thumbnail to attach. 
  8. $thumbnail_id = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = set_post_thumbnail($post, $thumbnail_id); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function set_post_thumbnail( $post, $thumbnail_id ) { 
  2. $post = get_post( $post ); 
  3. $thumbnail_id = absint( $thumbnail_id ); 
  4. if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) { 
  5. if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) 
  6. return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); 
  7. else 
  8. return delete_post_meta( $post->ID, '_thumbnail_id' ); 
  9. return false;