Skip to content

Instantly share code, notes, and snippets.

@fabriziosalmi
Created October 11, 2023 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabriziosalmi/3e81179176a26abfa4609e4f942f3c1b to your computer and use it in GitHub Desktop.
Save fabriziosalmi/3e81179176a26abfa4609e4f942f3c1b to your computer and use it in GitHub Desktop.
Wordpress Image Optimizer

Setup

  1. Create a new folder in your WordPress wp-content/plugins directory and name it image-optimizer.
  2. Inside this folder, create a PHP file named image-optimizer.php and paste the following code:
<?php
/**
 * Plugin Name: Image Optimizer
 * Description: Optimizes images in a given directory without loss of quality.
 * Version: 1.0
 * Author: Your Name
 */

// Hook for adding admin menus
add_action('admin_menu', 'image_optimizer_menu');

// Action function for the above hook
function image_optimizer_menu() {
    add_menu_page('Image Optimizer', 'Image Optimizer', 'manage_options', 'image_optimizer', 'image_optimizer_page');
}

// Function to display the admin page
function image_optimizer_page() {
    ?>
    <div class="wrap">
        <h2>Image Optimizer</h2>
        <form method="post" action="">
            <label for="directory">Directory Path:</label>
            <input type="text" id="directory" name="directory" required>
            <input type="submit" name="optimize_images" value="Optimize Images">
        </form>
        <?php
        if (isset($_POST['optimize_images'])) {
            $directory = sanitize_text_field($_POST['directory']);
            $result = optimize_images($directory);
            echo '<div id="message" class="updated notice is-dismissible"><p>' . $result . '</p></div>';
        }
        ?>
    </div>
    <?php
}

// Function to optimize images
function optimize_images($directory) {
    if (!class_exists('Imagick')) {
        return "Error: Imagick not installed.";
    }

    if (!is_dir($directory)) {
        return "Error: Invalid directory.";
    }

    $files = glob($directory . '/*.{jpg,png}', GLOB_BRACE);
    if (empty($files)) {
        return "Error: No image files found in the directory.";
    }

    $log = fopen(plugin_dir_path(__FILE__) . 'image_optimizer_log.txt', 'a');
    fwrite($log, "Optimization started at " . date('Y-m-d H:i:s') . "\n");

    foreach ($files as $file) {
        try {
            $image = new Imagick($file);
            $image->stripImage();
            $image->writeImage($file);
            $image->clear();
            $image->destroy();
            fwrite($log, "Optimized: " . $file . "\n");
        } catch (Exception $e) {
            fwrite($log, "Error optimizing: " . $file . " - " . $e->getMessage() . "\n");
        }
    }

    fclose($log);
    return "Images optimized successfully. Check the log for details.";
}
?>

How to Use

  1. Activate the Plugin: Go to the WordPress admin dashboard, navigate to "Plugins", and activate the "Image Optimizer" plugin.
  2. Use the Plugin: After activation, you'll see a new menu item called "Image Optimizer". Click on it, and you'll be taken to a page where you can enter the directory path of the images you want to optimize. After entering the path, click "Optimize Images".

Note: Make sure the Imagick PHP extension is installed and enabled on your server for this plugin to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment