参数
$post
int|WP_Post必填-
要附加缩略图的Post ID或Post对象。
$thumbnail_id
int必填-
要附加的缩略图。
返回
int|bool 成功时为true,失败时为false。
源码
更新日志
版本 | 描述 |
---|---|
3.1.0 | 开始引入 |
使用示例
要以编程方式将上载的图片文件设置为缩略图,可以使用以下代码…
/* * $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 ); } }
返回值不是:“成功时为true”
成功时,返回值是update_post_meta函数返回的新meta字段ID,如果delete_post_meta成功,则返回值为TRUE。
此方法将在第二次运行时返回false。如果特色图像已设置为您提供的附件ID,则该方法将返回false,因为`update_post_meta`在值不会更改时返回false。