Atomic Smash homepage splash

Creating your own image optimisation for WordPress [advanced]

Words by David DarkeAugust 20, 2017

TL;DR. Install this script via composer and setup a cronjob.

In a previous post, I compared different image optimisation plugins. The one avenue I didn’t explore was the possibility of creating your own from scratch (well almost from scratch¬†ūüėČ).

You will need SSH access to your server, so this probably isn’t applicable for anyone on shared hosting.

Image optimisation in it most basic form needs to:

  • Loop through a series on image automatically when they have been uploaded.
  • Don’t re-optimise¬†previously optimised images (compounding optimisation can dramatically affect image quality).
  • Allow for optimisation of previously uploaded images.

This is all very attainable using an image library (Jpegoptim), and scheduling the task in a custom bash script.

Why bother?

A lot of plugins tie directly¬†into WordPress and the WordPress admin UI (which can be a good thing) but the only access that WordPress has to files for quick manipulation is via its media library. If files don’t exist in the library, they won’t be optimised.

Atomic Smash uses¬†Timber for all of our sites and it provides it’s own bespoke image resizing functions. This removes the need in declaring thumbnail sizes within WordPress and allows you to generate cropped image on the fly when they are needed (rather than blindly producing crops that might never be used). The standard method mean WordPress knows the resized images exist (because they are in the library) but using Timber mean there are several unregistered crops available. So they inevitably get missed with performing ‘bulk’ optimisations in most plugins.

This disconnect between the file system and what WordPress actually knows about the media assets on the server doesn’t usually cause any issues, until now. Rolling your own optimisation lets you use the file system and not have to worry about the WordPress thumbnail crop registration.

It also means that this method will work with any CMS not just WordPress! It only cares about the images saved on the server, not what actually put them there.

Installing jpegoptim

Jpegoptim is the primary library used for the actual image optimisation. This is very simple to install via SSH:

apt-get install jpegoptim

To check it installed correctly, simply run…

 jpegoptim -help

… to make sure you receive the docs for¬†jpegoptim rather than an error.

Now installed, you should be able to use it via the command line, or within a bash script.

Create a script

This is the script we currently use:

#!/bin/bash

# cd to the location of this file
cd ${0%/*}
# cd back to the WP root, and out of the vendor folder
cd ../../../wp-content/uploads/

# See if optimisation is being forced
if [ -z "$1" ]; then
    find=$(find * -mtime -3 -name '*.jpg' -or -name '*.JPG')
else
    find=$(find * -name '*.jpg' -or -name '*.JPG')
fi


# find JPEGs
for f in $find; do
    # Simple filter to grab WP cropped image, it looks for
    # [number][number][the letter x][number][number]
    # This sequence appears at the end of WP cropped images like:
    # 2016/09/structured-data-in-wordpress-392x250.jpg
    if [[ $f =~ [0-9][0-9]\x[0-9][0-9] ]] ; then
        # echo $f;
        jpegoptim $f --preserve --max=84
    fi
done

The core of the work are these 3 lines:

for f in $find; do
    if [[ $f =~ [0-9][0-9]\x[0-9][0-9] ]] ; then
        jpegoptim $f --preserve --max=84

Here is a break down of what is actually happening line by line:

  1. Loop through a previously defined folder. In most instances this will be the ‘wp-content/uploads’ folder of your site.
  2. Line 2 does a quick test on the filename, if it contains a set of numbers, followed the letter ‘x’ then followed by another set of numbers, then continue with the resize. This is a quick way to make sure originally uploaded (source images) aren’t modified, only cropped versions.*
  3. Run jpegoptim on the single image.

*So for example ‘2016/09/structured-data-in-wordpress-392×250.jpg’ would be optimised, but ‘2016/09/structured-data-in-wordpress.jpg’ would not.

Scheduling

Due to this being a server side script, you want it to run regularly in the background. The frequency of this action is completely up to you (we usually set it up to run every hour). run ‘crontab -e’ and add:

0 * * * * bash /path/to/the/script/image-optimise.sh

Within the main script, you can also modify the amount of compression by tweaking the ‘–max=84’ option on the line¬†‘jpegoptim $f –preserve –max=84’.

We have started rolling this script out to a good number of our WordPress sites with some very positive results and decreased page load times.

Composer

This script is available via composer, just add :

"logsmith/image-optimisation": "*",

… inside your composer file and update!

Profile picture of David Darke

David Darke

As the lead developer and co-founder at Atomic Smash. David’s wealth of knowledge in website development means that all sites work seamlessly across desktop, tablet and mobile devices.

Go back to top

Keep up to date with Atomic news