您可以使用wp\\u insert\\u attachment()函数提供的示例codex page 和set\\u post\\u缩略图()too :
$file = $_FILES[\'thumbnail\'][\'tmp_name\'];
/*
* $filename is the path to your uploaded file (for example as set in the $_FILE posted file array)
* $file 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 ) );
if ( ! $upload_file[\'error\'] ) {
// Check the type of file. We\'ll use this as the \'post_mime_type\'.
$filetype = wp_check_filetype( $filename, null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
\'post_mime_type\' => $filetype[\'type\'],
\'post_title\' => preg_replace( \'/\\.[^.]+$/\', \'\', $filename ),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'post_parent\' => $post_id
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $upload_file[\'file\'], $post_id );
if ( ! is_wp_error( $attachment_id ) ) {
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_file[\'file\'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}
}