Sitemap
Volodymyr Zhyliaev

Volodymyr Zhyliaev

Human, man, thinker, money maker. Owner of https://digitalowl.top/ Interests: books, history, it, WordPress, marketing, SEO etc

Plugin for Automatic Image Optimization

3 min readOct 9, 2024

--

Press enter or click to view image in full size

In the world of web development, optimizing images is crucial for ensuring fast load times and a smooth user experience. An automatic image optimization plugin can help compress and optimize images when they are uploaded, significantly improving your website’s performance. This guide will walk you through creating a WordPress plugin that automatically optimizes images during the upload process.

Features:

  • Compress images upon upload
  • Optimize JPEG, PNG, and GIF formats
  • Set optimization levels for different image formats
  • Ability to regenerate thumbnails for existing images

Step-by-Step Guide to Building the Plugin

Step 1: Create the Plugin Files

Create a new folder named automatic-image-optimization in the wp-content/plugins/ directory. Inside this folder, create a PHP file named automatic-image-optimization.php with the following plugin header:

<?php
/**
* Plugin Name: Automatic Image Optimization
* Description: Automatically optimizes images upon upload for better performance.
* Version: 1.0
* Author: Your Name
*/

// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}

Get Volodymyr Zhyliaev’s stories in your inbox

Join Medium for free to get updates from this writer.

Step 2: Implement Image Compression on Upload

We will use the wp_handle_upload filter to optimize images during the upload process. Add the following code to your plugin file:

// Function to optimize images upon upload
function aio_optimize_image($file) {
// Check if the file is an image
$image_types = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($file['type'], $image_types)) {
$image_path = $file['tmp_name'];

// Load the image based on its type
if ($file['type'] == 'image/jpeg') {
$image = imagecreatefromjpeg($image_path);
imagejpeg($image, $image_path, 75); // Compress JPEG to 75% quality
} elseif ($file['type'] == 'image/png') {
$image = imagecreatefrompng($image_path);
imagepalettetotruecolor($image);
imagealphablending($image, false);
imagesavealpha($image, true);
imagepng($image, $image_path, 6); // Compress PNG with a compression level of 6
} elseif ($file['type'] == 'image/gif') {
$image = imagecreatefromgif($image_path);
imagegif($image, $image_path); // GIFs are not compressed further
}

imagedestroy($image); // Free up memory
}

return $file; // Return the file to continue the upload process
}
add_filter('wp_handle_upload_prefilter', 'aio_optimize_image');

Read also: How to Create a WordPress Plugin: An A-Z Guide https://volodymyrzh.medium.com/how-to-create-a-wordpress-plugin-an-a-z-guide-184e804107c5

Step 3: Add Options for Optimization Levels

To give users control over optimization settings, we’ll add a settings page in the WordPress admin. Create a settings menu and add a form to set optimization levels. Here’s how to do that:

// Function to add admin menu
function aio_add_admin_menu() {
add_options_page('Image Optimization', 'Image Optimization', 'manage_options', 'image-optimization', 'aio_options_page');
}
add_action('admin_menu', 'aio_add_admin_menu');

// Function to display the settings page
function aio_options_page() {
?>
<div class="wrap">
<h1>Image Optimization Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('aio_options_group');
do_settings_sections('aio_options_group');
?>
<label for="jpeg_quality">JPEG Quality:</label>
<input type="number" name="jpeg_quality" value="<?php echo esc_attr(get_option('jpeg_quality', 75)); ?>" min="1" max="100" /><br/>

<label for="png_compression">PNG Compression Level:</label>
<input type="number" name="png_compression" value="<?php echo esc_attr(get_option('png_compression', 6)); ?>" min="0" max="9" /><br/>

<?php submit_button(); ?>
</form>
</div>
<?php
}

// Function to register settings
function aio_register_settings() {
register_setting('aio_options_group', 'jpeg_quality');
register_setting('aio_options_group', 'png_compression');
}
add_action('admin_init', 'aio_register_settings');

Step 4: Use the User’s Settings in the Compression Code

Modify the compression code to use the values set in the settings page. Update the image optimization function as follows:

function aio_optimize_image($file) {
$image_types = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($file['type'], $image_types)) {
$image_path = $file['tmp_name'];

// Get the optimization settings
$jpeg_quality = get_option('jpeg_quality', 75);
$png_compression = get_option('png_compression', 6);

if ($file['type'] == 'image/jpeg') {
$image = imagecreatefromjpeg($image_path);
imagejpeg($image, $image_path, $jpeg_quality);
} elseif ($file['type'] == 'image/png') {
$image = imagecreatefrompng($image_path);
imagepalettetotruecolor($image);
imagealphablending($image, false);
imagesavealpha($image, true);
imagepng($image, $image_path, $png_compression);
} elseif ($file['type'] == 'image/gif') {
$image = imagecreatefromgif($image_path);
imagegif($image, $image_path);
}

imagedestroy($image);
}

return $file;
}
add_filter('wp_handle_upload_prefilter', 'aio_optimize_image');

Step 5: Finalizing the Plugin

After implementing these features, thoroughly test the plugin to ensure it works as expected. Activate it from the WordPress admin dashboard under Plugins and monitor its performance.

Conclusion

This simple WordPress plugin automatically optimizes images during upload, enhancing your website’s performance. While the optimization methods included are basic, they lay the groundwork for a more sophisticated image optimization solution. Always keep your plugin updated and consider integrating with external image optimization services for even better results.

--

--

Written by Volodymyr Zhyliaev

Human, man, thinker, money maker. Owner of https://digitalowl.top/ Interests: books, history, it, WordPress, marketing, SEO etc