transient-cleanup.php
| 1 | <?php |
| 2 | /* |
| 3 | Adapted from Purge Transients by Seebz |
| 4 | https://github.com/Seebz/Snippets/tree/master/Wordpress/plugins/purge-transients |
| 5 | */ |
| 6 | if ( ! function_exists( 'jp_purge_transients' ) ) { |
| 7 | |
| 8 | /** |
| 9 | * Jetpack Purge Transients. |
| 10 | * |
| 11 | * @access public |
| 12 | * @param string $older_than (default: '1 hour') Older Than. |
| 13 | * @return void |
| 14 | */ |
| 15 | function jp_purge_transients( $older_than = '1 hour' ) { |
| 16 | global $wpdb; |
| 17 | $older_than_time = strtotime( '-' . $older_than ); |
| 18 | if ( $older_than_time > time() || $older_than_time < 1 ) { |
| 19 | return false; |
| 20 | } |
| 21 | $sql = $wpdb->prepare( " |
| 22 | SELECT REPLACE(option_name, '_transient_timeout_jpp_', '') AS transient_name |
| 23 | FROM {$wpdb->options} |
| 24 | WHERE option_name LIKE '\_transient\_timeout\_jpp\__%%' |
| 25 | AND option_value < %d |
| 26 | ", $older_than_time ); |
| 27 | $transients = $wpdb->get_col( $sql ); |
| 28 | $options_names = array(); |
| 29 | foreach ( $transients as $transient ) { |
| 30 | $options_names[] = '_transient_jpp_' . $transient; |
| 31 | $options_names[] = '_transient_timeout_jpp_' . $transient; |
| 32 | } |
| 33 | if ( $options_names ) { |
| 34 | $option_names_string = implode( ', ', array_fill( 0, count( $options_names ), '%s' ) ); |
| 35 | $delete_sql = "DELETE FROM {$wpdb->options} WHERE option_name IN ($option_names_string)"; |
| 36 | $delete_sql = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $delete_sql ), $options_names ) ); |
| 37 | $result = $wpdb->query( $delete_sql ); |
| 38 | if ( ! $result ) { |
| 39 | return false; |
| 40 | } |
| 41 | } |
| 42 | return; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Jetpack Purge Transients Activation. |
| 48 | * |
| 49 | * @access public |
| 50 | * @return void |
| 51 | */ |
| 52 | function jp_purge_transients_activation() { |
| 53 | if ( ! wp_next_scheduled( 'jp_purge_transients_cron' ) ) { |
| 54 | wp_schedule_event( time(), 'daily', 'jp_purge_transients_cron' ); |
| 55 | } |
| 56 | } |
| 57 | add_action( 'admin_init', 'jp_purge_transients_activation' ); |
| 58 | add_action( 'jp_purge_transients_cron', 'jp_purge_transients' ); |
| 59 |