对于每个图像/帖子组合,请运行以下命令。$image_name
是文件名,$post_id
是帖子ID。
if( $image_name != \'\' && !has_post_thumbnail( $post_id ) ){
$base = get_stylesheet_directory();
$imgfile= $base . \'/import/\' . $image_name; // Images are stored inside an imports folder, in the theme directory
$filename = basename($imgfile);
$upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
if (!$upload_file[\'error\']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_parent\' => 0,
\'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)) {
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 );
}
}
如果处理大量图像/帖子,可能会遇到PHP超时。如果是这样,只需再次运行该函数。有一个已经附加的图像检查,所以这应该不是一个问题。