search ]

Schedule Cron to Delete Expired Transients

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.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo