post thumbnail migration code
<?php
$the_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 20,
'offset' => 0,
) );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
if (get_the_post_thumbnail_url(get_the_ID(), 'full')) continue;
// $filename はアップロード用ディレクトリにあるファイルのパス。
$filename = '/path/to/hoge.png';
// この添付ファイルを紐付ける親投稿の ID。
$parent_post_id = get_the_ID();
// ファイルの種類をチェックする。これを 'post_mime_type' に使う。
$filetype = wp_check_filetype( basename( $filename ), null );
// アップロード用ディレクトリのパスを取得。
$wp_upload_dir = wp_upload_dir();
// 添付ファイル用の投稿データの配列を準備。
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// 添付ファイルを追加。
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// wp_generate_attachment_metadata() の実行に必要なので下記ファイルを含める。
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// 添付ファイルのメタデータを生成し、データベースを更新。
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
// アイキャッチ画像にする。
set_post_thumbnail( $parent_post_id, $attach_id );
echo '<p style="display:none;">'.$filename.':'.$parent_post_id.':'.$attach_id.'</p>';
endwhile;
endif;
wp_reset_postdata();
?>