How to call NS Cloner to Copy Sites from Other Plugins Documentation

Have you ever wondered if there is an API or some way to automatically clone a site with PHP instead of using the NS Cloner interface?

Well, there is!

First, the setup:

/**
 * Before doing anything: set up clone request data.
 * These are the same fields that get submitted via an AJAX request when cloning
 * via the admin interface, so you can inspect that request to determine other
 * ways to configure the parameters, particularly if you're using NS Cloner Pro
 * and have more options available.
 * $request = array(
 *     'clone_mode'     => 'core',
 *     'source_id'      => 1, // any blog/site id on network
 *     'target_name'    => 'subdomain-or-subdir,
 *     'target_title'   => 'New Site Title',
 *     'debug'          => 1 // optional: enables logs
 * }
 */

// Load WordPress (ONLY if invoking this from outside WordPress)
// other plugins and themes do NOT need to do this.
require( wp-load.php );

There are now two ways to run the Cloner:

  1. Immediately.
    • Pro: you can check for errors or success and access the result of the operation.
    • Con: will fail if another cloning process is already running.
  2. Scheduled.
    • Pro: control over timing, and will queue itself gracefully if another operation is running.
    • Con: there’s no easy way to access or verify the outcome of the operation.
// Method 1: immediate.
// ###################

// Register request with the cloner.
foreach ( $request as $key => $value ) {
   ns_cloner_request()->set( $key, $value );
}

// Get the cloner process object.
$cloner = ns_cloner()->process_manager;

// Begin cloning.
$cloner->init();

// Check for errors (from invalid params, or already running process).
$errors = $cloner->get_errors();
if ( ! empty( $errors ) ) {
   // Handle error(s) and exit
}

// Last you'll need to poll for completion to run the cleanup process
// when content is done cloning. Could be via AJAX to avoid timeout, or like:
do {
   // Attempt to run finish, if content is complete.
   $pm->maybe_finish();
   $progress = $pm->get_progress();
   // Pause, so we're not constantly hammering the server with progress checks.
   sleep( 3 );
} while ( 'reported' !== $progress['status'] );

// Once you've verified that $progress['status'] is 'reported',
// you can get access the array of report data (whether successful or failed) via:
$reports = ns_cloner()->report->get_all_reports();

OR (don’t do both 1 and 2):

// Method 2: scheduled.
// ####################
ns_cloner()->schedule->add(
   $request,          // array of request data as specified above
   time(),            // timestamp of date/time to start cloning - use time() to run immediately
   'Your Plugin Name' // name of your project, required but used only for debugging
);