A wp-cli command with a progress bar and an exit code

Anything run more than twice against a site is better as a command than as an admin page with a button, and two details make one people will trust.

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    WP_CLI::add_command( 'turkerdev reindex', function ( $args, $assoc ) {
        $ids      = turkerdev_pending_ids( (int) ( $assoc['limit'] ?? 500 ) );
        $progress = WP_CLIUtilsmake_progress_bar( 'Reindexing', count( $ids ) );
        $failed   = 0;

        foreach ( $ids as $id ) {
            if ( ! turkerdev_index( $id ) ) {
                ++$failed;
            }

            $progress->tick();
        }

        $progress->finish();

        if ( $failed ) {
            WP_CLI::error( sprintf( '%d failed', $failed ) );   // exit code 1
        }

        WP_CLI::success( sprintf( '%d indexed', count( $ids ) ) );
    } );
}

The progress bar is the difference between a command people wait for and one they kill after ninety seconds assuming it hung. WP_CLI::error sets a non-zero exit code and halts, which is what makes the command usable from a deploy script rather than only by a human. The defined guard keeps the file harmless when it is loaded by a web request, which it will be.