- Create a new folder in your WordPress
wp-content/plugins
directory and name itimage-optimizer
. - 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.";
}
?>
- Activate the Plugin: Go to the WordPress admin dashboard, navigate to "Plugins", and activate the "Image Optimizer" plugin.
- 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.