Skip to content

Instantly share code, notes, and snippets.

@indikatordesign
Last active December 5, 2022 13:12
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 indikatordesign/6356390c61e1705e409f60135007a5bb to your computer and use it in GitHub Desktop.
Save indikatordesign/6356390c61e1705e409f60135007a5bb to your computer and use it in GitHub Desktop.
WordPress - Delete expired transients
<?php
/**
* Do not allow direct access
*
* @since 1.0
*/
if ( ! defined( 'ABSPATH' ) ) die( 'Nothing to find Ma\'am..' );
/**
* Your Plugin Name - Model Transients
*
* @since 1.0
*/
if ( ! class_exists( 'modelTransients' ) )
{
final class modelTransients
{
/**
* Set properties
*
* @since 1.0
*/
private $wpdb;
/**
* Constructor
*
* @since 1.0
*/
public function __construct()
{
global $wpdb;
$this->wpdb = $wpdb;
} // end constructor
/**
* Clear expired transients
*
* @since 1.0
*/
public function expiredTransients()
{
$query = "Select * FROM {$this->wpdb->options} WHERE option_name LIKE '%_transient_timeout_%'";
$rows = $this->wpdb->get_results( $query );
$time = time() - MINUTE_IN_SECONDS;
foreach ( $rows as $row ) :
if ( (int) $row->option_value < $time )
$arr[] = $row->option_name;
endforeach;
if ( isset( $arr ) )
foreach ( $arr as $key => $transient )
delete_transient( str_replace( '_transient_timeout_', '', $transient ) );
} // end expiredTransients
} // end class
} // end if
/**
* Your Plugin Name - Controller Helpers
*
* @since 1.0
*/
if ( ! class_exists( 'controllerHelpers' ) )
{
final class controllerHelpers
{
/**
* Get the next 12:00 am timestamp
*
* @since 1.0
*/
public function twelveTimestamp()
{
$time = time();
$hour = (int) date( 'H', $time );
if ( $hour >= 11 ) // to be sure
$add = 24 - $hour + 2; // next day
if ( isset( $add ) )
$setTarget = date( 'Y-m-d', $time + ( $add * HOUR_IN_SECONDS ) ) . ' 12:00:00';
else
$setTarget = date( 'Y-m-d', $time ) . ' 12:00:00';
return DateTime::createFromFormat( 'Y-m-d H:i:s', $setTarget )->getTimestamp();
} // end twelveTimestamp
} // end class
} // end if
//It makes sense to set it to a sheduled hook
$prefix = 'my_pref';
if ( ! wp_next_scheduled( $prefix . '_scheduled_hook' ) )
wp_schedule_event( ( new controllerHelpers )->twelveTimestamp(), 'daily', $prefix . '_scheduled_hook' );
add_action( $prefix . '_scheduled_hook', [ ( new modelTransients ), 'expiredTransients' ] );
//To clear the sheduled hook
$time = wp_next_scheduled( $prefix . '_scheduled_hook' );
wp_unschedule_event( $time, $prefix . '_scheduled_hook' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment