Skip to content

Instantly share code, notes, and snippets.

@michael-cannon
Forked from ScottPhillips/purge-wp-transients.php
Last active November 23, 2019 11:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michael-cannon/4491140 to your computer and use it in GitHub Desktop.
Save michael-cannon/4491140 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Purge Transients
Description: Purge old transients
Version: 0.1
Author: Seebz
*/
if ( ! function_exists('purge_transients') ) {
function purge_transients($older_than = '1 day', $safe_mode = true) {
global $wpdb;
$older_than_time = strtotime('-' . $older_than);
if ($older_than_time > time() || $older_than_time < 1) {
return false;
}
$transients = $wpdb->get_col(
$wpdb->prepare( "
SELECT REPLACE(option_name, '_transient_timeout_', '') AS transient_name
FROM {$wpdb->options}
WHERE option_name LIKE '\_transient\_timeout\__%%'
AND option_value < %s
", $older_than_time)
);
if ( empty( $safe_mode) ) {
foreach($transients as $transient) {
delete_transient( $transient );
}
}
return $transients;
}
}
function purge_transients_activation () {
if (!wp_next_scheduled('purge_transients_cron')) {
wp_schedule_event( time(), 'daily', 'purge_transients_cron');
}
}
register_activation_hook(__FILE__, 'purge_transients_activation');
function my_plugin_deactivation () {
if (wp_next_scheduled('purge_transients_cron')) {
wp_clear_scheduled_hook('purge_transients_cron');
}
}
register_deactivation_hook(__FILE__, 'purge_transients_deactivation');
function do_purge_transients_cron () {
purge_transients();
}
add_action('purge_transients_cron', 'do_purge_transients_cron');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment