Skip to content

Instantly share code, notes, and snippets.

@unaibamir
Created July 23, 2018 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unaibamir/d190a372a091f414fd879aff752f2a23 to your computer and use it in GitHub Desktop.
Save unaibamir/d190a372a091f414fd879aff752f2a23 to your computer and use it in GitHub Desktop.
<?php
function isa_add_cron_recurrence_interval( $schedules ) {
$schedules['every_single_minute'] = array(
'interval' => MINUTE_IN_SECONDS,
'display' => __( 'Every Single Minute', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_cron_recurrence_interval' );
// Schedule the CRON Job to purge all expired transients
if (!wp_next_scheduled('purge_popup_transients_cron')) {
/**
* wp_schedule_event
*
* @param - When to start the CRON job
* @param - The interval in for each subsequent run
* @param - The name of the CRON JOB
*/
wp_schedule_event( time(), 'every_single_minute', 'purge_popup_transients_cron');
}
add_action( 'purge_popup_transients_cron', 'purge_transients', 10 ,2);
/**
* Deletes all transients that have expired
*
* @access public
* @static
* @return void
*/
function purge_transients($older_than = '1 minute', $safemode = true) {
global $wpdb;
$older_than_time = strtotime('-' . $older_than);
/**
* Only check if the transients are older than the specified time
*/
if ( $older_than_time > time() || $older_than_time < 1 ) {
return false;
}
/**
* Get all the expired transients
*
* @var mixed
* @access public
*/
$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 safemode is ON just use the default WordPress get_transient() function
* to delete the expired transients
*/
if ( $safemode ) {
foreach( $transients as $transient ) {
get_transient($transient);
}
}
/**
* If safemode is OFF the just manually delete all the transient rows in the database
*/
else {
$options_names = array();
foreach($transients as $transient) {
$options_names[] = '_transient_' . $transient;
$options_names[] = '_transient_timeout_' . $transient;
}
if ($options_names) {
$options_names = array_map(array($wpdb, 'escape'), $options_names);
$options_names = "'". implode("','", $options_names) ."'";
$result = $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name IN ({$options_names})" );
if (!$result) {
return false;
}
}
}
return $transients;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment