Create your own wp command, like wp nahnu cleanup, to run site maintenance tasks from the terminal.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
/**
* Clean up expired transients and old auto-drafts.
*
* ## OPTIONS
*
* [--dry-run]
* : Show what would be deleted without deleting anything.
*
* ## EXAMPLES
*
* wp nahnu cleanup
* wp nahnu cleanup --dry-run
*/
WP_CLI::add_command( 'nahnu cleanup', function ( array $args, array $assoc_args ): void {
$dry_run = (bool) WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', false );
$drafts = get_posts( [
'post_status' => 'auto-draft',
'post_type' => 'any',
'date_query' => [ [ 'before' => '7 days ago' ] ],
'fields' => 'ids',
'posts_per_page' => -1,
] );
WP_CLI::log( sprintf( 'Old auto-drafts: %d', count( $drafts ) ) );
if ( $dry_run ) {
WP_CLI::success( 'Dry run: nothing deleted.' );
return;
}
foreach ( $drafts as $id ) {
wp_delete_post( $id, true );
}
delete_expired_transients( true );
WP_CLI::success( 'Cleanup complete.' );
} );
}
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
WP-CLI is the fastest way to run maintenance on a WordPress site, and it’s easy to add your own commands. They run with WordPress fully loaded, so you can use any WordPress function.
The code only runs when WordPress is loaded by WP-CLI, which defines the WP_CLI constant. WP_CLI::add_command() registers the command name and the function to run.
The comment block above it becomes the command’s help text, shown by wp help nahnu cleanup. The [--dry-run] option there is read with get_flag_value().
WP_CLI::log() prints output and WP_CLI::success() prints a green success message.
wp nahnu cleanup --path=/var/www/site.In a terminal, in your site folder, run wp nahnu cleanup --dry-run. You should see the count of old auto-drafts and a success message.