if (defined('WP_CLI') && WP_CLI) { function register_set_featured_image_command() { WP_CLI::add_command('set-featured-image', function () { global $wpdb; $last_processed_id = (int) get_option('set_featured_image_last_processed_id', 0); $batch_size = 50; // Number of posts to process per batch while (true) { $posts = $wpdb->get_results($wpdb->prepare(" SELECT p.ID, p.post_content FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_thumbnail_id' WHERE p.post_status = 'publish' AND p.post_type = 'post' AND pm.meta_value IS NULL AND p.post_content LIKE '%% %d ORDER BY p.ID ASC LIMIT %d ", $last_processed_id, $batch_size)); if (empty($posts)) { WP_CLI::success("All posts without featured images have been processed. No more posts to process."); break; } foreach ($posts as $post) { WP_CLI::log("Processing post ID: {$post->ID}"); if (preg_match('/]+src=["\']([^"\'>]+)["\']/', $post->post_content, $match)) { $image_url = $match[1]; WP_CLI::log("Extracted image URL: {$image_url}"); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $image_id = media_sideload_image($image_url, $post->ID, null, 'id'); if (!is_wp_error($image_id)) { set_post_thumbnail($post->ID, $image_id); WP_CLI::success("Set featured image for post ID {$post->ID} using image URL: {$image_url}."); } else { WP_CLI::warning("Failed to download image for post ID {$post->ID}. Error: " . $image_id->get_error_message()); } } else { WP_CLI::warning("No valid tag found in post ID {$post->ID}."); } $last_processed_id = $post->ID; update_option('set_featured_image_last_processed_id', $last_processed_id); } WP_CLI::log("Batch processed. Continuing to the next batch..."); } }); } register_set_featured_image_command(); }{"id":8443,"count":4,"description":"","link":"https:\/\/www.theindustry.biz\/tag\/ella-langley\/","name":"Ella Langley","slug":"ella-langley","taxonomy":"post_tag","meta":[],"_links":{"self":[{"href":"https:\/\/www.theindustry.biz\/wp-json\/wp\/v2\/tags\/8443","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.theindustry.biz\/wp-json\/wp\/v2\/tags"}],"about":[{"href":"https:\/\/www.theindustry.biz\/wp-json\/wp\/v2\/taxonomies\/post_tag"}],"wp:post_type":[{"href":"https:\/\/www.theindustry.biz\/wp-json\/wp\/v2\/posts?tags=8443"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}