Home > Dev > WordPress Optimization > Automatically Deleting Expired Transients

Automatically Deleting Expired Transients

This code will delete expired transients automatically using a scheduled event.

if (!wp_next_scheduled('delete_expired_transients')) {
    wp_schedule_event(time(), 'daily', 'delete_expired_transients');
}

add_action('delete_expired_transients', 'delete_all_expired_transients');

function delete_all_expired_transients() {
    global $wpdb;
    $expired = $wpdb->get_col(
        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()"
    );

    foreach ($expired as $transient) {
        $key = str_replace('_transient_timeout_', '', $transient);
        delete_transient($key);
    }
}
Back