Remove expired WordPress Transients with WP-CLI

WP-CLI can be used to perform all kinds of tasks on your WordPress website. I use it to regularly clean my database of expired transients via a Linux cronjob. By using WP-CLI, I can perform this task safely and automatically!

Note: this can only be done when you have shell-access to the webserver you are managing.

First you need to install WP-CLI. How to do that is explained here. After you’ve installed WP-CLI, you have to find the folder of the WordPress website.

In my case the folder of the website is located at:

/home/mvandek/mvandek.nl/

To remove the expired WordPress Transients from the database of this website, I use the following command:

/usr/local/bin/wp --path=/home/mvandek/mvandek.nl transient delete --expired --allow-root

The following parameters are used:

  • –path= – this is the folder where WordPress is installed
  • transient – tells WP-CLI to use the Transient module
  • delete – tells WP-CLI to delete the Transients in the database
  • –expired – tells WP-CLI to only delete the expired Transients. These aren’t automatically removed and thus can stay in the database while expired
  • –allow-root – normally you have to run this command from the user that manages the website. I add this so that I can run this command from the shell

I use the path /usr/local/bin/wp instead of the command wp. By doing this I’m sure I won’t get any errors when executing this task.

Next, I have to determine when I want to run this cronjob. This can be executed at the following moments:

  • @hourly – every hour of every day
  • @daily – every day at 0:00
  • @weekly – everey sunday at 0:00
  • @monthly – every first day of the month at 0:00
  • @yearly – every frist day of the first month at 0:00
  • @annualy – same as @yearly

So, to be sure that the removal of the expired transients is done regularly, I chose to use @daily.

The command to remove the expired Transiens will be:

@daily /usr/local/bin/wp --path=/home/maartenvandekamp/www.maartenvandekamp.nl transient delete --expired --allow-root

Add this line of code to crontab via the following command:

crontab -e

Add the line to this file and leave the editor.

Crontab will now make a new job that will be executed every day at 0:00, and will send the output to the root user.

If you don’t want to be notified of the output, you have to add the following code after the origininal command

> /dev/null 2>&1

The complete line will be:

@daily /usr/local/bin/wp --path=/home/maartenvandekamp/www.maartenvandekamp.nl transient delete --expired --allow-root > /dev/null 2>&1