get_error_message() ) ); } $file_array = array( 'name' => self::file_name( $temp_file, $title ), 'tmp_name' => $temp_file, ); $attachment_id = media_handle_sideload( $file_array, $post_id, $title ); if ( is_wp_error( $attachment_id ) ) { wp_delete_file( $temp_file ); throw new \RuntimeException( esc_html( $attachment_id->get_error_message() ) ); } update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $title ) ); update_post_meta( $attachment_id, DraftMapping::AI_GENERATED, 1 ); set_post_thumbnail( $post_id, $attachment_id ); return (int) $attachment_id; } /** * Ein Dateiname mit der Endung, die zum tatsaechlichen Inhalt passt. * * Der Weg ueber media_sideload_image() verlangt eine Bildendung in der URL; Aivor * liefert Bilder auch ohne. Deshalb wird die Endung aus dem Inhalt * bestimmt. * * @param string $temp_file Heruntergeladene Datei. * @param string $title Beitragstitel. * @return string */ private static function file_name( string $temp_file, string $title ): string { $extensions = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', 'image/avif' => 'avif', ); $mime = (string) wp_get_image_mime( $temp_file ); $extension = $extensions[ $mime ] ?? 'jpg'; $base = sanitize_title( $title ); if ( '' === $base ) { $base = 'aivor-image'; } return substr( $base, 0, 80 ) . '.' . $extension; } }