Optimize PNG Files in the WordPress Uploads Folder with Grunt

Grunt is a JavaScript based taskrunner that runs on node.js and automates repetitive development tasks. Grunt has a ton of plugins that automate basically just about anything and everything. Just a few examples of Grunt automation are minifying js scripts and CSS files, compiling SCSS, linting and image optimization.

I’m going to show you how to create a simple grunt setup that optimizes all the images in your WordPress uploads folder. WordPress already does a great job of optimizing .jpgs when they are uploaded through the media library. However, WordPress doesn’t compress or optimize png files. PNG files tend to look better, but  are bigger in file size and cause slow load times. Slow load times cause a bad user experience and can also hurt your SEO. I also use a grunt version of Yahoo SmushIt to further optimize .jpgs as well as .pngs.

The required software for this tutorial is as follows:

Step 1: Install Node.js and Grunt

Please make sure that you install the Grunt Command Line Interface (CLI) as well!

Step 2: Set up the Environment

Create a folder named ‘grunt-image-optimizer’. The folder could technically be anywhere, but I have created a folder on my desktop with multiple subfolders that each contain specific Grunt tasks. This approach makes repurposing automated tasks really convenient.

In our grunt-image-optimizer folder we need to create two files. The first file is our package.json. This file only needs the name and version number of your project. The devDependencies are automatically added to package.json Grunt and Grunt plugins are installed.

  1. Create a new file named package.json in the folder. Paste this snippet into the newly created file:
    {
      "name": "Image-Optimizer",
      "version": "1.0.0",
      "devDependencies": {}
    }
  2. Next we need to install Grunt and the grunt plugins that we need to execute the script. To install grunt, navigate to the ‘grunt-image-optimizer’ folder in Terminal then copy and paste this snippet into Terminal:
    npm install grunt --save-dev

    Then to install grunt-pngmin, copy and paste this into Terminal:

    npm install grunt-pngmin --save-dev

    Then to install grunt-smushit, copy and paste this into Terminal:

    npm install grunt-smushit --save-dev
  3. Create a file in the ‘grunt-image-optimizer’ folder and name it gruntfile.js. Then copy and paste this code into gruntfile.js:
    module.exports = function(grunt) {
    	grunt.initConfig({
        	pkg: grunt.file.readJSON('package.json'),
    
    		pngmin: {
    		
    			compile: {
    				options: {
    					ext: '.png',
    					force: true
    				},
    			
    					files: [{
    						expand: true, // required option
    						src: ['**/*.png'],
    						cwd: 'uploads/', // required option
    						dest: 'uploads/'
    					}]
    				}
    			},
    	
    			smushit: {
    				mygroup: {
    					src: ['uploads/**/*.jpg', 'uploads/**/*.png'],
    					dest: 'uploads/'
    				}
    			}
      	
    	});
    
    grunt.loadNpmTasks('grunt-pngmin');
    grunt.loadNpmTasks('grunt-smushit');
    
    grunt.registerTask('default', ['pngmin', 'smushit']);
    
    }
    
    

That’s it for the setting up the environment!

Step 3: Get your WordPress Uploads Folder in Place for the the Image Optimization

This step is really easy. Download your WordPress Uploads directory to the folder with your grunt files. I also like to create a duplicate copy of the Uploads folder to compare the sizes and the file count.

This is what the ‘grunt-image-optimizer’ folder structure with the Grunt files should look like at this point of the tutorial:

-grunt-image-optimizer
--gruntfile.js
--node_modules
---grunt
---grunt-pngming
---grunt-smushit
--package.json
--uploads
--uploads-duplicate

Step 4: Run Grunt

Type the following command into Terminal and hit enter:

grunt

This will execute the the grunt scripts that have been set up in gruntfile.js.

Step 5: Compare File Count Before and After

I always check the number of files in ‘uploads’ and ‘uploads-duplicate’ when grunt is finished running. This number NEEDS to match 100%. If it doesn’t, then you need to problem solve before uploading/merging the optimized files back into your WordPress site.

Step 6: Uploading the Optimized image files to your WordPress site

You can upload the optimized images once you have confirmed that same number of files exist in both the uploads and uploads-duplicate folders. There are multiple ways of approaching this task, but I typically follow these steps:

  1. Rename the Uploads folder on your local machine to “uploads-new”.
  2. Upload “uploads-new” to your wp-content folder.
  3. Once “uploads-new” is finished uploading, rename the current “uploads” folder to “uploads-backup”
  4. Then rename “uploads-new” to “uploads”

Final Thoughts

That’s it! Your site is now pulling in optimized images and you also have a backup of the original uploads folder on the server. I have created a zip file of the folder I use to optimize images if you would like to try it out before getting more into Grunt. Please be aware that you will still need to install node.js and the Grunt command line tool before the contents of the zip file will execute.

One thought to “Optimize PNG Files in the WordPress Uploads Folder with Grunt”

Leave a Reply

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