WP-CLI: Require confirmation for search-replace

Worried about accidentally running a real search-replace command? Here’s how you can require confirmation for live-runs:

In your config file, add this:

require:
  - /path/to/search-replace-confirmation.php

In /path/to/search-replace-confirmation.php, add this:

<?php

$configurator = \WP_CLI::get_configurator();
$argv = array_slice( $GLOBALS['argv'], 1 );
list( $args, $assoc_args, $runtime_config ) = $configurator->parse_args( $argv );


$help          = array_search( 'help', $args );
$searchreplace = array_search( 'search-replace', $args );
$dry_run       = array_search( 'dry-run',  $assoc_args );

if (
    false !== $searchreplace && // is search-replace
    false === $dry_run && // isn't already dry run
    ( false === $help || $help > $searchreplace ) // isn't help command
) {
    WP_CLI::confirm( 'Proceed with live run?' );
}

Leave a Reply

Your email address will not be published. Required fields are marked *