当前浏览:首页 / WordPress函数 / set_post_thumbnail()

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

设置给定文章的文章缩略图(特色图像)

postmore...

setmore...

thumbnail 缩略图


参数

$postint|WP_Post必填
要附加缩略图的Post ID或Post对象。
$thumbnail_idint必填
要附加的缩略图。

返回

int|bool 成功时为true,失败时为false。



源码

查看源码 官方文档


更新日志

版本描述
3.1.0开始引入

使用示例

  • 示例1

    要以编程方式将上载的图片文件设置为缩略图,可以使用以下代码…

    /*
     * $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_get_contents( $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_check_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/image.php');
    
         $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
    
         wp_update_attachment_metadata( $attachment_id,  $attachment_data );
         set_post_thumbnail( $post_id, $attachment_id );
       }
    }
  • 示例2

    返回值不是:“成功时为true”

    成功时,返回值是update_post_meta函数返回的新meta字段ID,如果delete_post_meta成功,则返回值为TRUE。

  • 示例3

    此方法将在第二次运行时返回false。如果特色图像已设置为您提供的附件ID,则该方法将返回false,因为`update_post_meta`在值不会更改时返回false。