Examples
Real-world code samples for WPZylos WP-CLI.
Data Migration Command
use WP_CLI;
class MigrateDataCommand
{
public function __construct(
private DataMigrationService $migrator
) {}
/**
* Migrate data from old format.
*
* ## OPTIONS
*
* [--batch-size=<size>]
* : Number of records per batch
* ---
* default: 100
* ---
*
* [--dry-run]
* : Preview without making changes
*/
public function run(array $args, array $assocArgs): void
{
$batchSize = (int) ($assocArgs['batch-size'] ?? 100);
$dryRun = isset($assocArgs['dry-run']);
if ($dryRun) {
WP_CLI::warning('DRY RUN - No changes will be made');
}
$total = $this->migrator->count();
$progress = \WP_CLI\Utils\make_progress_bar('Migrating', $total);
foreach ($this->migrator->batches($batchSize) as $batch) {
foreach ($batch as $record) {
if (!$dryRun) {
$this->migrator->migrate($record);
}
$progress->tick();
}
}
$progress->finish();
WP_CLI::success("Migrated {$total} records.");
}
}
Cleanup Command
use WP_CLI;
class CleanupCommand
{
/**
* Clean up old data.
*/
public function run(array $args, array $assocArgs): void
{
WP_CLI::confirm('Delete all records older than 30 days?');
$deleted = DB::table('logs')
->where('created_at', '<', date('Y-m-d', strtotime('-30 days')))
->delete();
WP_CLI::success("Deleted {$deleted} old records.");
}
}
Export Command
use WP_CLI;
class ExportCommand
{
/**
* Export data to CSV.
*
* ## OPTIONS
*
* <type>
* : Data type (users, orders, products)
*
* [--output=<file>]
* : Output file path
* ---
* default: export.csv
* ---
*/
public function run(array $args, array $assocArgs): void
{
$type = $args[0];
$output = $assocArgs['output'] ?? 'export.csv';
$exporter = $this->getExporter($type);
$count = $exporter->export($output);
WP_CLI::success("Exported {$count} {$type} to {$output}");
}
}