How to Convert Image Upload png,jpg to Avif without Plugin

AVIF (AV1 Image File Format) is one of the most efficient modern image formats — offering smaller file sizes and better quality than WebP or JPEG.
If you want WordPress to automatically convert uploaded images (like JPG or PNG) into AVIF without installing any plugins, you can easily do it using PHP’s Imagick extension and a simple code snippet.

This method hooks into the WordPress media upload process, detects when an image is uploaded, converts it to AVIF, and replaces the original file details.

How to Convert PNG and JPG to AVIF In WordPress Without a Plugin

Requirements

Before you start, make sure your hosting environment supports:

  1. PHP 8.0+
  2. Imagick extension installed and enabled (php-imagick must support AVIF)
  3. WordPress (any version 5.8+)

You can check if Imagick supports AVIF using this small test:

<?php
$imagick = new Imagick();
echo implode(', ', $imagick->queryFormats());
?>

If AVIF appears in the list, you’re good to go

Add the Code Snippet

Add the following code to your theme’s functions.php file or a custom functionality plugin:

How It Works

  1. Hook:
    The code uses the wp_handle_upload filter, which triggers after a file is uploaded.
  2. Check file type:
    It processes only JPEG, PNG, and WebP images.
  3. Imagick conversion:
    If the Imagick PHP module is available, it loads the uploaded image, converts it to AVIF format, and saves it as a new file.
  4. Replace upload info:
    WordPress then replaces the uploaded file details (file, url, and type) with the new .avif image path — so WordPress treats the AVIF file as the actual upload.

Optional: Adjusting Quality

You can tweak the compression quality here:

$img->setImageCompressionQuality(60);

100 = best quality, largest file

60 = good balance for web use

30 = smaller size, more compression

Troubleshooting

  • Error: “AVIF conversion failed” → Check if your server’s Imagick library supports AVIF.
  • Images not showing in browser → Ensure your server sends the correct MIME type (image/avif).
  • Slow conversion → Large images may take longer; you can optimize them before upload.

optional

here’s the complete single code snippet you can drop directly into your theme’s functions.php or a custom plugin.

This version:
✅ Converts uploaded JPG/PNG/WebP to AVIF using Imagick
✅ Keeps the original file as fallback
✅ Automatically serves AVIF with fallback using <picture> tags
✅ Works across all modern and older browsers

<?php
/**
 * Convert uploaded images (JPG, PNG, WebP) to AVIF
 * and serve them with fallback using <picture> tag
 * No plugin required
 */

// 1️⃣ Convert uploaded images to AVIF and keep original as fallback
add_filter('wp_handle_upload', 'convert_image_to_avif_with_fallback', 10, 2);
function convert_image_to_avif_with_fallback($upload, $context) {
    $file = $upload['file'];
    $type = $upload['type'];

    // Only convert common image formats
    if (in_array($type, ['image/jpeg', 'image/png', 'image/webp'])) {
        if (class_exists('Imagick')) {
            try {
                $img = new Imagick($file);
                $img->setImageFormat('avif');
                $img->setImageCompressionQuality(60); // adjust quality (0–100)

                // Save AVIF alongside the original
                $avif_file = preg_replace('/\.(jpe?g|png|webp)$/i', '.avif', $file);
                $img->writeImage($avif_file);
                $img->destroy();

                // Save the AVIF file URL in image metadata for later use
                $avif_url = preg_replace('/\.(jpe?g|png|webp)$/i', '.avif', $upload['url']);
                update_post_meta(
                    attachment_url_to_postid($upload['url']),
                    '_avif_version',
                    $avif_url
                );

            } catch (Exception $e) {
                error_log('AVIF conversion failed: ' . $e->getMessage());
            }
        }
    }
    return $upload;
}

// 2️⃣ Automatically serve AVIF with fallback using <picture> tag
add_filter('wp_get_attachment_image', 'serve_avif_with_fallback', 10, 5);
function serve_avif_with_fallback($html, $attachment_id, $size, $icon, $attr) {
    $avif_url = get_post_meta($attachment_id, '_avif_version', true);
    if ($avif_url) {
        // Extract original <img> src
        preg_match('/src="([^"]+)"/', $html, $matches);
        $fallback_src = isset($matches[1]) ? $matches[1] : '';

        if ($fallback_src) {
            $picture = '<picture>
                <source srcset="' . esc_url($avif_url) . '" type="image/avif">
                <source srcset="' . esc_url($fallback_src) . '" type="image/jpeg">
                ' . $html . '
            </picture>';
            return $picture;
        }
    }
    return $html;
}

// 3️⃣ Optional: Allow AVIF uploads in WordPress media library (if you also upload AVIF manually)
add_filter('mime_types', function($mimes) {
    $mimes['avif'] = 'image/avif';
    return $mimes;
});

How to Use

  1. Copy the full code above.
  2. Paste it into your functions.php (or use a “Code Snippets” plugin).
  3. Upload a new image via Media → Add New.
  4. WordPress will:
    • Create both .jpg and .avif versions.
    • Automatically serve <picture> markup with fallback.

Conclusion

That’s it! You’ve now set up automatic AVIF conversion in WordPress — no plugin required.
Every new image you upload will be stored in the more efficient AVIF format, saving bandwidth and improving your site’s performance.

Read More wp hacks here

Share your love
The Fallen
The Fallen
Articles: 73

Leave a Reply

Your email address will not be published. Required fields are marked *

hii
index
0%

How did you reach us?