Attach image to WP post

При постинге через wp-rest featured image не аттачится к посту. В статусе каринки стоит unattached, у неё нет post_parent.

Сниппет для привзки всех картинок к их постам. Делает по 50 картинок за раз при page reload в админке.

add_action('admin_init', function () {

// Запускать только для админа
if (!current_user_can('manage_options')) {
return;
}

// Остановить, если уже всё сделали
if (get_option('attach_featured_done')) {
return;
}

// Размер батча
$batch_size = 50;

// С какой позиции начинаем (сохраняем прогресс)
$offset = (int) get_option('attach_featured_offset', 0);

$posts = get_posts([
'post_type' => ['post'], // добавь сюда CPT, если нужно
'posts_per_page' => $batch_size,
'offset' => $offset,
'post_status' => 'any',
'fields' => 'ids',
]);

if (empty($posts)) {
update_option('attach_featured_done', 1);
return;
}

foreach ($posts as $post_id) {
$thumb_id = get_post_thumbnail_id($post_id);

if (!$thumb_id) {
continue;
}

$current_parent = wp_get_post_parent_id($thumb_id);
if ($current_parent == $post_id) {
continue;
}

wp_update_post([
'ID' => $thumb_id,
'post_parent' => $post_id,
]);
}

// Сохранить новый offset
update_option('attach_featured_offset', $offset + $batch_size);
});

Можно сделать через CLI > wp-cli.yml:

if (defined('WP_CLI') && WP_CLI) {
WP_CLI::add_command('attach-featured', function () {

$query = new WP_Query([
'post_type' => ['post'], // добавь CPT
'posts_per_page' => 200,
'post_status' => 'any',
'fields' => 'ids',
'no_found_rows' => true,
]);

$count = 0;

foreach ($query->posts as $post_id) {
$thumb_id = get_post_thumbnail_id($post_id);

if (!$thumb_id) {
continue;
}

$current_parent = wp_get_post_parent_id($thumb_id);
if ($current_parent == $post_id) {
continue;
}

wp_update_post([
'ID' => $thumb_id,
'post_parent' => $post_id,
]);

$count++;
}
WP_CLI::success("Updated {$count} attachments.");
});
}