Transients are extremely useful – most WordPress developers use them to cache frequently used data, but many don’t realize that transients aren’t automatically deleted once they expire and can slow down the site.
If you are not 100% familiar with the WordPress Transient API then feel free to revisit the well documented WordPress codex entry.
The Problem
The main problem about WordPress transients is that once they expire they are not automatically deleted. They are only deleted when you try to retrieve a transient that has an expired value. So technically, if you create a transient and then never reference again, it will remain in your database forever. This can drastically increase the size of your wp_options table, which in turn can slow down your site. So how do we fix this problem and delete expired transients from the wp_options table?
The Solution
To purge expired transients on a daily basis, simply add the code below into the functions.php file or any custom functions file called by the theme. Or, create a small plugin file to handle it on its own.
The above code will delete all expired transients on a daily basis, but you can adjust it to a schedule that fits your needs. This is extremely useful for developers who use dynamic transients (i.e. storing data based on someone’s IP address as a transient value).
Please let us know your thoughts and if you know a better way to solve this problem :)
4 Responses
Hi Kyle, I this code into a plugin I’m building and got an error:
Parse error: syntax error, unexpected T_FUNCTION, expecting T_PAAMAYIM_NEKUDOTAYIM
I cleared the error by removing the ‘static’ in front of the purge_popup_transients function.
I have a question. The ‘purge_transients_cron’ action calls a function called ‘purge_transients’ but the name of your function is ‘purge_popup_transients’. Is there something I’m not seeing here or do I need to make those match? I ask because I haven’t worked with wp_cron much and don’t know what I don’t know.
Besides that I think this is an extremely useful script! Thanks for sharing it!
Hi Kyle, I also noticed the name given to the scheduled event is ‘purge_popup_transients_cron’ and the action is hooked to ‘purg_transients_cron’. Do these need to match as well?
Why not just use a WP cleanup/optimize plugin? Don’t they clean up anything unnecessary, including expired transients, etc?
@Robin – some people like to use plugins for everything; others like to understand how things actually work, and tend to write up their own when practical.