Using WordPress ‘delete_expired_transients()’ PHP function

The delete_expired_transients() WordPress PHP function deletes all expired transients. However, it’s important to note that this function won’t perform any action if an external object cache is in use. It uses multi-table delete syntax to remove the transient record from one table (let’s call it table a), and the corresponding transient_timeout record from another table (let’s say table b).

Usage

delete_expired_transients($force_db);

In the above example, $force_db is a boolean parameter. When set to true, the function will force cleanup to run against the database, even when an external object cache is in use. By default, it is false.

Parameters

  • $force_db (bool) – Optional. This parameter forces cleanup to run against the database even when an external object cache is in use. Default is false.

More information

See WordPress Developer Resources: delete_expired_transients()
This function has been implemented since WordPress version 4.9. It is not deprecated and is still in use as of the last update. The source code can be found in wp-includes/option.php.

Examples

Default Usage

This is a simple usage of the function without any parameter. It will delete all expired transients if no external object cache is in use.

delete_expired_transients();

Forcing Database Cleanup

In this example, we’re forcing the function to delete expired transients from the database regardless of any external object cache.

delete_expired_transients(true);

Conditional Cleanup

Here, we’re only forcing the database cleanup if a certain condition is met, say, the user is an admin.

if (current_user_can('administrator')) {
    delete_expired_transients(true);
}

Scheduled Cleanup

This code sets up a scheduled event that runs the delete_expired_transients function every hour.

if (! wp_next_scheduled ( 'my_hourly_event' )) {
    wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}

add_action('my_hourly_event', 'delete_expired_transients');

Cleanup Upon Deactivation

Finally, this example shows how to delete all expired transients upon plugin deactivation.

register_deactivation_hook( __FILE__, 'delete_expired_transients' );

Each of these examples provides a practical usage of the delete_expired_transients() function based on different requirements and scenarios.