post_content ); $modified = false; // Iterate through the blocks to find the ai-image/block. foreach ( $blocks as &$block ) { if ( 'ai-image/block' === $block['blockName'] && isset( $block['attrs']['imageUrl'] ) ) { $image_url = $block['attrs']['imageUrl']; // Download the image and save it to the media library. $response = wp_remote_get( $image_url ); if ( is_wp_error( $response ) ) { continue; } $image_data = wp_remote_retrieve_body( $response ); $image_type = wp_remote_retrieve_header( $response, 'content-type' ); if ( ! $image_data || ! $image_type ) { continue; } // Use WordPress file handling. // Sanitize the image name. $image_name = sanitize_file_name( uniqid( 'ai-image-', true ) . '.jpg' ); $upload = wp_upload_bits( $image_name, null, $image_data ); if ( $upload['error'] ) { continue; } // Set up media attachment array. $attachment = array( 'post_mime_type' => $image_type, 'post_title' => sanitize_file_name( basename( $image_url ) ), 'post_content' => '', 'post_status' => 'inherit', 'guid' => $upload['url'], ); // Insert the attachment and generate metadata. $attachment_id = wp_insert_attachment( $attachment, $upload['file'], $post_id ); require_once ABSPATH . 'wp-admin/includes/image.php'; $metadata = wp_generate_attachment_metadata( $attachment_id, $upload['file'] ); wp_update_attachment_metadata( $attachment_id, $metadata ); // Replace ai-image/block with core/image block. $new_image_url = wp_get_attachment_url( $attachment_id ); $block = array( 'blockName' => 'core/image', 'attrs' => array( 'id' => $attachment_id, 'sizeSlug' => 'full', 'linkDestination' => 'none', ), 'innerContent' => array( '
', ), ); $modified = true; } } // Update post content if modified. if ( $modified ) { $post->post_content = serialize_blocks( $blocks ); remove_action( 'save_post', 'ai_image_save_to_media_library_on_save' ); wp_update_post( $post ); add_action( 'save_post', 'ai_image_save_to_media_library_on_save' ); } } add_action( 'save_post', 'flarex_replace_ai_image_block_with_core_image_on_save' );