add_action('save_post', 'process_autoblogging_images'); function process_autoblogging_images($post_id) { if (wp_is_post_revision($post_id)) { return; } remove_action('save_post', 'process_autoblogging_images'); $post = get_post($post_id); $post_content = $post->post_content; preg_match_all('/]*?src\s*=\s*([\'"])(https?:\/\/files\.autoblogging\.ai[^\'"]+)\1[^>]*?>/i', $post_content, $matches, PREG_SET_ORDER); $featured_image_set = has_post_thumbnail($post_id); $upload_dir = wp_upload_dir(); $post_title = sanitize_title($post->post_title); foreach ($matches as $match) { $image_url = $match[2]; $image_data = file_get_contents($image_url); $filename = $post_title . '-' . wp_generate_password(2, false) . '.' . pathinfo($image_url, PATHINFO_EXTENSION); $filename = wp_unique_filename($upload_dir['path'], $filename); $file = $upload_dir['path'] . '/' . $filename; file_put_contents($file, $image_data); $alt_text = ''; preg_match('/alt=[\'"](.*?)[\'"]/i', $match[0], $alt_matches); if (isset($alt_matches[1])) { $alt_text = $alt_matches[1]; } $attachment = array( 'guid' => $upload_dir['url'] . '/' . $filename, 'post_mime_type' => 'image/jpeg', 'post_title' => $alt_text, 'post_content' => '', 'post_status' => 'inherit', 'post_excerpt' => $alt_text, ); $attachment_id = wp_insert_attachment($attachment, $file, $post_id); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attachment_id, $file); wp_update_attachment_metadata($attachment_id, $attach_data); if (!$featured_image_set) { set_post_thumbnail($post_id, $attachment_id); $featured_image_set = true; $post_content = preg_replace('/' . preg_quote($match[0], '/') . '/', '', $post_content, 1); continue; } $new_url = wp_get_attachment_url($attachment_id); $post_content = str_replace($match[2], $new_url, $post_content); } wp_update_post(array( 'ID' => $post_id, 'post_content' => $post_content, )); add_action('save_post', 'process_autoblogging_images'); }