Over time, expired transients pile up in the wp_options table and slow down queries. This snippet schedules a weekly cleanup. For more on improving WordPress performance.
if ( ! wp_next_scheduled( 'savvy_cleanup_transients' ) ) {
wp_schedule_event( time(), 'weekly', 'savvy_cleanup_transients' );
}
add_action( 'savvy_cleanup_transients', function () {
global $wpdb;
$wpdb->query(
"DELETE a, b FROM {$wpdb->options} a
LEFT JOIN {$wpdb->options} b
ON b.option_name = REPLACE( a.option_name, '_transient_timeout_', '_transient_' )
WHERE a.option_name LIKE '\_transient\_timeout\_%'
AND a.option_value < UNIX_TIMESTAMP()"
);
} );Add to functions.php. The cron runs once a week and removes only expired transients.