Questa è una versione PDF del contenuto. Per la versione completa e aggiornata, visita:
https://blog.tuttosemplice.com/en/avif-wordpress-optimization-guide-and-custom-plugin/
Verrai reindirizzato automaticamente...
AVIF optimization for WordPress has become a top priority for developers and system administrators aiming for maximum web performance . In an ecosystem where loading speed dictates search engine ranking and user experience, relying on outdated image formats represents an unacceptable bottleneck. This technical guide explores the impact of the AVIF format and provides a ready-to-use programmatic solution to automate conversion on your server.
For decades, the web has relied on a duopoly: JPEG for photographs and PNG for images with transparency. Although the WebP format has been an excellent step forward in recent years, the evolution of video codecs has led to a new benchmark standard.
The AVIF (AV1 Image File Format) is derived from the open-source AV1 video codec. The technical advantages over its predecessors are drastic:
Images make up over 60% of a web page's payload on average. Optimizing them means directly acting on the metrics that Google uses to evaluate the Page Experience.
The correlation between AVIF and SEO is mainly evident in the Largest Contentful Paint (LCP) . Since the LCP element is often a hero image or banner, reducing its weight by 50% means drastically anticipating the moment the browser completes its rendering.
Reducing the image payload using next-generation codecs is the architectural intervention with the highest ROI for optimizing web performance and passing the Core Web Vitals.
Furthermore, the compatibility issue has now been overcome. Today, browser support is universal: Chrome, Firefox, Safari (from iOS 16/macOS Ventura), and Edge natively support the rendering of .avif files, making complex fallback systems using the <picture> tag unnecessary in most modern scenarios.
Starting with version 6.5, WordPress introduced native support for AVIF. This means that you can upload an .avif file to the Media Library, and the CMS will correctly generate the intermediate sizes (thumbnail, medium, large) in the same format.
However, there is a crucial problem: WordPress does not automatically convert JPEG or PNG files to AVIF when they are uploaded. If a content editor uploads a large JPEG, it will remain a JPEG.
Additionally, image generation depends on the graphics libraries installed on the server (ImageMagick or GD). If your server stack (e.g., a Docker container or an outdated VPS) has a version of ImageMagick compiled without libheif support, WordPress will silently fail to handle AVIF.
To solve the problem at its root, the best practice is to intercept the file upload, check the server's capabilities, and force programmatic conversion to AVIF before WordPress generates the metadata and intermediate sizes.
Here is the complete, secure, and commented source code for a custom plugin ( wp-custom-avif-converter.php ):
<?php /** * Plugin Name: WP Custom AVIF Converter * Description: Intercetta l'upload di JPEG/PNG e li converte automaticamente in AVIF. * Version: 1.0.0 * Author: Senior Web Performance Optimizer */ // 1. Controllo iniziale di sicurezza defined('ABSPATH') || exit; // 2. Hook per intercettare il file appena caricato add_filter('wp_handle_upload', 'wp_custom_convert_to_avif_on_upload'); function wp_custom_convert_to_avif_on_upload($upload) { // Verifica che l'upload sia andato a buon fine if (isset($upload['error']) || empty($upload['file'])) { return $upload; } $file_path = $upload['file']; $mime_type = $upload['type']; // 3. Intercetta solo i formati standard da convertire if (!in_array($mime_type, ['image/jpeg', 'image/png'])) { return $upload; } // 4. Verifica la presenza delle librerie di sistema if (!function_exists('wp_get_image_editor')) { return $upload; } $editor = wp_get_image_editor($file_path); if (is_wp_error($editor)) { return $upload; } // 5. Verifica se ImageMagick o GD supportano la codifica AVIF if (!wp_image_editor_supports(['mime_type' => 'image/avif'])) { error_log('WP AVIF Converter: Il server non supporta la codifica AVIF (richiesto ImageMagick con libheif o GD aggiornato).'); return $upload; } // 6. Genera il nuovo percorso file con estensione .avif $avif_path = preg_replace('/.(jpg|jpeg|png)$/i', '.avif', $file_path); // 7. Esegue la conversione $editor->set_quality(75); // Qualità ottimale per AVIF $saved = $editor->save($avif_path, 'image/avif'); if (!is_wp_error($saved)) { // Rimuove il file originale pesante @unlink($file_path); // Aggiorna l'array di upload affinché WP processi il nuovo file AVIF // per generare tutte le dimensioni intermedie nativamente $upload['file'] = $avif_path; $upload['url'] = preg_replace('/.(jpg|jpeg|png)$/i', '.avif', $upload['url']); $upload['type'] = 'image/avif'; } else { // 8. Gestione pulita degli errori error_log('WP AVIF Converter: Fallimento conversione - ' . $saved->get_error_message()); } return $upload; }#<?php /** * Plugin Name: WP Custom AVIF Converter * Description: Intercetta l'upload di JPEG/PNG e li converte automaticamente in AVIF. * Version: 1.0.0 * Author: Senior Web Performance Optimizer */ // 1. Controllo iniziale di sicurezza defined('ABSPATH') || exit; // 2. Hook per intercettare il file appena caricato add_filter('wp_handle_upload', 'wp_custom_convert_to_avif_on_upload'); function wp_custom_convert_to_avif_on_upload($upload) { // Verifica che l'upload sia andato a buon fine if (isset($upload['error']) || empty($upload['file'])) { return $upload; } $file_path = $upload['file']; $mime_type = $upload['type']; // 3. Intercetta solo i formati standard da convertire if (!in_array($mime_type, ['image/jpeg', 'image/png'])) { return $upload; } // 4. Verifica la presenza delle librerie di sistema if (!function_exists('wp_get_image_editor')) { return $upload; } $editor = wp_get_image_editor($file_path); if (is_wp_error($editor)) { return $upload; } // 5. Verifica se ImageMagick o GD supportano la codifica AVIF if (!wp_image_editor_supports(['mime_type' => 'image/avif'])) { error_log('WP AVIF Converter: Il server non supporta la codifica AVIF (richiesto ImageMagick con libheif o GD aggiornato).'); return $upload; } // 6. Genera il nuovo percorso file con estensione .avif $avif_path = preg_replace('/.(jpg|jpeg|png)$/i', '.avif', $file_path); // 7. Esegue la conversione $editor->set_quality(75); // Qualità ottimale per AVIF $saved = $editor->save($avif_path, 'image/avif'); if (!is_wp_error($saved)) { // Rimuove il file originale pesante @unlink($file_path); // Aggiorna l'array di upload affinché WP processi il nuovo file AVIF // per generare tutte le dimensioni intermedie nativamente $upload['file'] = $avif_path; $upload['url'] = preg_replace('/.(jpg|jpeg|png)$/i', '.avif', $upload['url']); $upload['type'] = 'image/avif'; } else { // 8. Gestione pulita degli errori error_log('WP AVIF Converter: Fallimento conversione - ' . $saved->get_error_message()); } return $upload; }
Enter the average size of your current images to calculate the estimated server savings.
The deployment of this solution is extremely fast and does not require any database configurations:
wp-custom-avif-converter inside /wp-content/plugins/ . Save the provided code in a wp-custom-avif-converter.php file inside the folder. Alternatively, you can upload the file directly to the /wp-content/mu-plugins/ (Must-Use Plugins) directory to make it un-deactivatable by standard users. To verify that it's working, open your browser's Developer Tools (F12), go to the Network tab, and filter by "Img". Reload the page where you inserted the image: you should see that the "Type" column shows image/avif and the file size is drastically reduced. Finally, run a test on PageSpeed Insights to measure the actual improvement in the LCP metric.
Integrating the AVIF format into WordPress via a custom plugin is an elegant and definitive solution for reducing the weight of web pages. By automating server-side conversion, human error during content editing is eliminated, ensuring that every multimedia resource served to users is optimized for the highest performance standards required by Core Web Vitals.
The AVIF format is derived from the open-source AV1 video codec and represents the new standard for images on the web. Compared to WebP, it offers a weight saving of up to 50% for the same visual quality, while also handling transparency and colors in a superior way. This reduction drastically improves loading times and fundamental metrics for search engine positioning.
To automate the conversion, you can create a custom PHP plugin that intercepts media file uploads. This script checks the server's capabilities and converts JPEG or PNG files to AVIF before the system generates thumbnails. This eliminates manual work and ensures that every resource is optimized for maximum performance.
To properly process this new-generation format, your hosting space must have updated graphics libraries. Specifically, you need an ImageMagick version compiled with libheif support or a recent GD library. Without these technical requirements at the server level, the system will fail the conversion and keep the heavier original formats.
Although recent versions of the CMS natively support this format, the system only generates intermediate sizes while maintaining the original file type. If you upload a photograph in JPEG format, the software will always create thumbnails in JPEG without optimizing them. To force a change of format during upload, it is necessary to intervene with a dedicated programmatic solution.
Currently, the compatibility of this format has become universal and covers all major modern browsers. Users can view these images without problems on Chrome, Firefox, Edge, and Safari, starting from iOS 16 and macOS Ventura operating systems. Therefore, it is no longer necessary to implement complex fallback systems in the HTML code to ensure correct display.