WordPress WebP Converter

  • Main Functionality:

    • Automatically converts uploaded images (JPEG, PNG, GIF, HEIC) to WebP format when files are uploaded to WordPress
    • Uses the Imagick PHP extension to perform the conversion
    • Only keeps the WebP version if it's smaller than the original file

    Key Features:

    • Image Resizing: Automatically resizes images to configurable maximum dimensions (default: 1920x1080) while maintaining aspect ratio
    • Quality Control: Allows setting compression quality (1-100, default: 80)
    • Orientation Correction: Fixes image rotation issues based on EXIF data
    • Size Optimization: Only saves the WebP version if it's smaller than the original
    • Admin Settings: Adds configuration options to the WordPress Media settings page

    Admin Interface:

    • Shows notices on upload/media pages about whether WebP conversion is enabled/disabled
    • Warns if the required Imagick extension isn't installed
    • Provides settings fields for max width/height and compression quality
    • Includes a checkbox to enable/disable the conversion feature

    Smart Behavior:

    • Only processes images if the feature is enabled
    • Skips conversion if Imagick isn't available
    • Deletes the original file only if WebP conversion is successful and results in a smaller file
    • Handles various image orientations automatically

    This plugin is useful for WordPress sites wanting to automatically optimize images for faster loading while maintaining quality, as WebP typically provides better compression than traditional formats.

  • Snippet

    id || 'media' === $screen->id) {
    if (!extension_loaded('imagick')) {
    echo "<div><p><strong>Warning:</strong> The Imagick PHP extension required for WebP conversion is not installed or enabled. Please install or enable Imagick.</p></div>";
    } else {
    $settings_url = admin_url('options-media.php');
    $webp_conversion_enabled = get_option('mbwpc_convert_to_webp', false);

    if ($webp_conversion_enabled) {
    echo "<div><p><strong>Enabled:</strong> WebP image conversion is active. You can disable this feature on the <a>Settings &gt; Media</a> page.</p></div>";
    } else {
    echo "<div><p><strong>Disabled:</strong> WebP image conversion is not active. You can enable this feature on the <a>Settings &gt; Media</a> page.</p></div>";
    }
    }
    }
    }

    /**
    * Register settings for WebP conversion and image processing.
    */
    function mbwpc_register_settings() {
    register_setting('media', 'mbwpc_convert_to_webp', [
    'type' =&gt; 'boolean',
    'sanitize_callback' =&gt; 'rest_sanitize_boolean',
    'default' =&gt; false,
    ]);

    register_setting('media', 'mbwpc_max_width', [
    'type' =&gt; 'integer',
    'sanitize_callback' =&gt; 'absint',
    'default' =&gt; 1920,
    ]);

    register_setting('media', 'mbwpc_max_height', [
    'type' =&gt; 'integer',
    'sanitize_callback' =&gt; 'absint',
    'default' =&gt; 1080,
    ]);

    register_setting('media', 'mbwpc_compression_quality', [
    'type' =&gt; 'integer',
    'sanitize_callback' =&gt; function($value) {
    return max(1, min(100, absint($value)));
    },
    'default' =&gt; 80,
    ]);

    add_settings_field(
    'mbwpc_convert_to_webp',
    __('Convert Uploaded Images to WebP', 'mbwpc'),
    'mbwpc_field_callback',
    'media',
    'default',
    ['label_for' =&gt; 'mbwpc_convert_to_webp']
    );

    add_settings_field(
    'mbwpc_image_settings',
    __('Image Processing Settings', 'mbwpc'),
    'mbwpc_image_settings_callback',
    'media',
    'default'
    );
    }

    /**
    * Display the image processing settings fields with inline styles.
    */
    function mbwpc_image_settings_callback() {
    $maxWidth = get_option('mbwpc_max_width', 1920);
    $maxHeight = get_option('mbwpc_max_height', 1080);
    $compressionQuality = get_option('mbwpc_compression_quality', 80);

    echo '<fieldset style="border: 1px solid #ddd;padding: 15px;border-radius: 4px;background: #f9f9f9">';
    echo '<legend style="font-weight: bold;padding: 0 10px">Image Processing Options</legend>';

    echo '<p style="margin: 10px 0"><label for="mbwpc_max_width" style="width: 150px;font-weight: 500">Max Width (pixels):</label>';
    echo '</p>';

    echo '<p style="margin: 10px 0"><label for="mbwpc_max_height" style="width: 150px;font-weight: 500">Max Height (pixels):</label>';
    echo '</p>';

    echo '<p style="margin: 10px 0"><label for="mbwpc_compression_quality" style="width: 150px;font-weight: 500">Compression Quality (1-100):</label>';
    echo '</p>';

    echo '<p style="margin: 10px 0 0 0;font-size: 12px;color: #666;font-style: italic">Higher quality = larger file size. Recommended: 70-90 for photos, 90-100 for graphics.</p>';
    echo '</fieldset>';
    }

    /**
    * Display the WebP conversion setting field with inline styles.
    */
    function mbwpc_field_callback() {
    $value = get_option('mbwpc_convert_to_webp', false);
    echo '<div style="background: #f0f8ff;border: 1px solid #0073aa;border-radius: 4px;padding: 10px;margin: 5px 0">';
    echo '';
    echo '<label for="mbwpc_convert_to_webp" style="font-weight: 500">' . esc_html__('Enable automatic conversion of uploaded images to WebP format', 'mbwpc') . '</label>';
    echo '<p style="margin: 8px 0 0 22px;font-size: 12px;color: #555">WebP images are typically 25-50% smaller than JPEG/PNG while maintaining similar quality.</p>';
    echo '</div>';
    }

    /**
    * Handle the image upload and convert to WebP format.
    *
    * @param array $upload Array containing the upload data.
    * @return array Modified upload data.
    */
    function mbwpc_handle_upload_convert_to_webp($upload) {
    if (!get_option('mbwpc_convert_to_webp')) {
    return $upload; // Skip the conversion if not enabled
    }

    $maxWidth = get_option('mbwpc_max_width', 1920);
    $maxHeight = get_option('mbwpc_max_height', 1080);
    $compressionQuality = get_option('mbwpc_compression_quality', 80);

    $valid_types = ['image/jpeg', 'image/png', 'image/gif', 'image/heic'];

    if (in_array($upload['type'], $valid_types)) {
    $file_path = $upload['file'];

    if (extension_loaded('imagick')) {
    try {
    $imagick = new Imagick($file_path);

    // Adjust orientation based on EXIF data
    switch ($imagick-&gt;getImageOrientation()) {
    case Imagick::ORIENTATION_BOTTOMRIGHT:
    $imagick-&gt;rotateImage("#000", 180);
    break;
    case Imagick::ORIENTATION_RIGHTTOP:
    $imagick-&gt;rotateImage("#000", 90);
    break;
    case Imagick::ORIENTATION_LEFTBOTTOM:
    $imagick-&gt;rotateImage("#000", -90);
    break;
    }

    $imagick-&gt;setImageOrientation(Imagick::ORIENTATION_TOPLEFT);

    $originalWidth = $imagick-&gt;getImageWidth();
    $originalHeight = $imagick-&gt;getImageHeight();
    $aspectRatio = $originalWidth / $originalHeight;
    $newWidth = $originalWidth;
    $newHeight = $originalHeight;

    // Resize if image exceeds maximum dimensions
    if ($originalWidth &gt; $maxWidth || $originalHeight &gt; $maxHeight) {
    if ($newWidth &gt; $maxWidth) {
    $newWidth = $maxWidth;
    $newHeight = $newWidth / $aspectRatio;
    }
    if ($newHeight &gt; $maxHeight) {
    $newHeight = $maxHeight;
    $newWidth = $newHeight * $aspectRatio;
    }
    }

    // Apply resizing and WebP conversion
    $imagick-&gt;resizeImage($newWidth, $newHeight, Imagick::FILTER_LANCZOS, 1);
    $imagick-&gt;setImageFormat('webp');
    $imagick-&gt;setImageCompression(Imagick::COMPRESSION_JPEG);
    $imagick-&gt;setImageCompressionQuality($compressionQuality);

    // Generate new file path
    $file_info = pathinfo($file_path);
    $dirname = $file_info['dirname'];
    $filename = $file_info['filename'];
    $new_file_path = $dirname . '/' . $filename . '.webp';
    $imagick-&gt;writeImage($new_file_path);

    // Compare file sizes - only keep WebP if it's smaller
    $original_size = filesize($file_path);
    $new_size = filesize($new_file_path);

    if ($new_size clear();
    $imagick-&gt;destroy();

    } catch (Exception $e) {
    // Log error for debugging
    if (defined('WP_DEBUG') &amp;&amp; WP_DEBUG) {
    error_log('MBWPC WebP conversion failed: ' . $e-&gt;getMessage());
    }
    }
    } else {
    // Only show this message to admins in debug mode
    if (defined('WP_DEBUG') &amp;&amp; WP_DEBUG &amp;&amp; current_user_can('manage_options')) {
    add_action('admin_notices', function() {
    echo '<div class="notice notice-error"><p><strong>MBWPC:</strong> Imagick is not installed. WebP conversion cannot be performed.</p></div>';
    });
    }
    }
    }

    return $upload;
    }
    ?&gt;
Review Your Cart
0
Add Coupon Code
Subtotal