Skip to content

Instantly share code, notes, and snippets.

@lucymtc
Last active March 30, 2022 08:09
Show Gist options
  • Save lucymtc/7791703822c14619738eb27914e19637 to your computer and use it in GitHub Desktop.
Save lucymtc/7791703822c14619738eb27914e19637 to your computer and use it in GitHub Desktop.
wp cli process something in batches
/**
* Start point for CLI command to process some posts in batches
*
* ## EXAMPLES
*
* wp mycommand
*
* @subcommand process-posts
*
* @param array $args Positional arguments for the command.
* @param array $assoc_args Associative arguments for the command.
* @return void
*/
public function process_posts( $args, $assoc_args ) {
$batch_size = 250;
$sleep_time = 1; // seconds
$sleep_break_count = 100;
$offset = 0;
$items_processed = 0;
$dry_run = ! empty( $assoc_args['dry-run'] );
do {
$args = [
//some other args for WP_Query...
'cache_results' => false,
'offset' => $offset,
'no_found_rows' => true,
'posts_per_page' => $batch_size
];
$query = new \WP_Query( $args );
if ( $query->post_count > 0 ) {
foreach ( $query->posts as $post_id ) {
$items_processed++;
// some logic.....
if ( ! $dry_run ) {
// some logic to update DB data if not dry run
\WP_CLI::line( '[ID: ' . $post_id . '] some message' );
}
}
$offset += $batch_size;
if ( $items_processed % $sleep_break_count == 0 ) {
sleep( $sleep_time );
}
} else {
break;
}
} while ( $query->post_count > 0 ) {
\WP_CLI::success( 'Done! ' . $items_processed . ' posts updated.' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment