To run a bulk operation across thousands of WordPress posts (recalculate a meta value, re-slug ten thousand products, backfill an optional field), put the code in a PHP file and run it with wp eval-file from the command line, not a script you hit in a browser. Batch the WP_Query, flush the object cache every batch, and make the per-row work safe to re-run. This guide covers that harness, the measured WP_Query memory and query tuning behind it, bulk imports with wp_insert_post that don't run out of memory, packaging the job as a custom WP-CLI command, and running AI enrichment over every post through a batch API at half the cost.
A browser-hit script runs as a web request, so it inherits PHP's max_execution_time, a single page load's memory limit, and a hard stop the moment the browser or a proxy gives up: halfway through you get a white screen and no idea which posts were processed.
wp eval-file has none of those limits. It loads WordPress fully and runs your file with no web-request timeout and whatever memory you give the CLI process. The catch is that WordPress was built to render one page and exit, so a long loop inside a single bootstrap accumulates memory in ways a normal request never reveals. This is the harness I use to keep a bulk run fast and flat on memory, whether it touches a hundred rows or a hundred thousand.
Why WP-CLI, not a browser script
wp eval-file path/to/script.php loads WordPress exactly as a request would (plugins, theme functions.php, the whole stack), then executes your file in the global scope. You get WP_Query, update_post_meta, every plugin's functions, all of it, with three things a browser hit can't give you:
- No execution timeout. CLI PHP defaults
max_execution_timeto0(unlimited). A 40-minute job is fine. - Real memory headroom. Set it per-invocation instead of fighting
php.ini. - Honest output.
WP_CLI::log()and exit codes, so a cron or a deploy script knows whether the job actually finished.
wp eval-file te-bulk-update.phpIf the job only needs core (no plugin hooks should fire during the run), skip the plugin load and it starts faster and behaves more predictably:
wp eval-file te-bulk-update.php --skip-plugins --skip-themesThe harness
Here is the shape I reach for. It processes posts in fixed-size batches, suspends the caches that only slow a write-heavy job down, and clears the object cache every batch so memory stays flat for the whole run.
<?php
/**
* te-bulk-update.php: WP-CLI bulk-operation harness.
*
* Run with: wp eval-file te-bulk-update.php
* Author: Ishan Karunaratne, https://techearl.com/wordpress-run-bulk-scripts-wp-cli
*/
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return; // Refuse to run anywhere but WP-CLI.
}
// Don't fill the object cache with entries this run will never read back.
// Invalidation stays ON, so every update_post_meta() still clears the cached
// copy and the site never serves a stale value from Redis or Memcached.
wp_suspend_cache_addition( true );
$batch_size = 200;
$paged = 1;
$processed = 0;
$started = microtime( true );
do {
$query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'any',
'posts_per_page' => $batch_size,
'paged' => $paged,
'fields' => 'ids', // Only pull IDs; don't hydrate full post objects.
'no_found_rows' => true, // Skip the SQL_CALC_FOUND_ROWS count we don't need.
'update_post_term_cache' => false, // te_bulk_apply() reads no terms.
'orderby' => 'ID',
'order' => 'ASC',
) );
if ( empty( $query->posts ) ) {
break;
}
// te_bulk_apply() reads meta, so prime the whole batch's meta in ONE query
// instead of one get_post_meta() round trip per post.
update_meta_cache( 'post', $query->posts );
foreach ( $query->posts as $post_id ) {
te_bulk_apply( (int) $post_id );
$processed++;
}
// Flush the runtime object cache and clear the saved-query log so neither
// grows without bound across batches. This is the line that keeps memory flat.
WP_CLI\Utils\wp_clear_object_cache();
WP_CLI::log( sprintf( 'Batch %d done: %d posts processed.', $paged, $processed ) );
$paged++;
} while ( true );
WP_CLI::success( sprintf(
'%d posts in %.1fs (%.0f/s).',
$processed,
microtime( true ) - $started,
$processed / max( microtime( true ) - $started, 0.001 )
) );
/**
* The actual per-post work. Replace the body with whatever the job needs.
*/
function te_bulk_apply( int $post_id ): void {
$price = (float) get_post_meta( $post_id, 'price', true );
if ( $price <= 0 ) {
return; // Idempotent skip: nothing to do for this row.
}
update_post_meta( $post_id, 'price_with_tax', round( $price * 1.2, 2 ) );
}Run it and the output reads like a progress bar you can trust:

The four things that actually matter
Strip the harness down and it comes to four decisions, each of which fixes a specific failure I have watched bulk jobs hit.
Batch the query, never posts_per_page => -1
-1 means "load every matching post into memory at once." On a few hundred rows it is fine; on fifty thousand it is an out-of-memory crash before the loop even starts. Pulling a fixed batch (paged + a sane posts_per_page) caps the working set no matter how big the table is. Pair it with 'fields' => 'ids' so each batch is an array of integers, not fully-hydrated WP_Post objects with their meta and terms eagerly loaded.
Turn off the bookkeeping the job doesn't read
A normal page render wants found_rows (for pagination) and the meta/term caches (because the template will ask for them). A write loop only wants the data its own work reads. 'no_found_rows' => true drops the second COUNT(*) query per batch, and 'update_post_term_cache' => false skips term data the job never touches. Meta is the exception here: the harness reads price, so it primes each batch's meta with one update_meta_cache() call (see the N+1 trap below for what happens otherwise).
Suspend the object cache for writes
wp_suspend_cache_addition( true ) stops WordPress adding new entries to the object cache during the run. In a write-heavy loop those entries are pure overhead because the job never reads them back, and skipping them is safe: anything not cached is simply read from the database next time.
wp_suspend_cache_invalidation() is the dangerous sibling, and I leave it off in the general harness. It stops WordPress clearing cache entries when data changes, and the WordPress reference puts the burden on the caller to make sure that doesn't leave the cache inconsistent. On a persistent object cache (Redis, Memcached), a post or meta value that was already cached before the run keeps serving the old value to every other request after the job finishes, until it expires. Clearing the CLI process's own runtime cache each batch does nothing for those other requests. It earns its place in one case, the one the reference names: a large import of new posts (the import pattern below uses it that way). Even there, cached query results and archive lists were never told the new posts exist, so once the import ends I call clean_post_cache() for the imported IDs (which also bumps the posts last_changed key that cached queries depend on), or flush the persistent cache once in a quiet window, never inside the loop. A job that updates existing posts needs the same cleanup for every post it changed.
Flush the object cache inside the loop
This is the non-obvious one, and it is why a job that looks fine on staging dies at 80% on production. Even with cache additions suspended, WordPress and many plugins hold references in the in-process object cache and in $wpdb->queries (when SAVEQUERIES is on). Across tens of thousands of iterations that quietly climbs until the process is killed. WP_CLI\Utils\wp_clear_object_cache() resets the runtime object cache and clears the saved-query log each batch, so memory traces a flat sawtooth instead of a ramp to the ceiling.
WP_Query performance and memory at scale
The harness's WP_Query arguments are not cargo cult; each one fixes a cost I measured. The numbers below are from a WP-CLI run over about 5,000 posts on a local site. Absolute figures vary by host; the ratios and the shape are what matter.
One big page vs batches
posts_per_page => -1 hydrates every matching post into a full WP_Post object at once, so peak memory grows linearly with the row count. Batching makes peak memory depend on the batch size, not the table size:

The naive run peaks at 119.8 MB, the batched-and-flushed run at 85.8 MB, for the same work at the same speed. The 34 MB gap is the 5,000 post objects held in memory simultaneously. Multiply the row count by ten and the naive peak climbs with it while the batched peak does not move. -1 is acceptable only for a small, bounded result you know will not grow, ideally with fields => ids; with full objects on a growing table it works in testing and runs out of memory in production a year later.
Cache priming and the N+1 trap
This is the knob people get backwards. When WP_Query returns full post objects it primes the meta cache for the whole page in one query (a single WHERE post_id IN (...)). Setting 'fields' => 'ids' and 'update_post_meta_cache' => false skips that prime, which is a win only if you do not then read meta. Read a meta value per row after disabling it and every get_post_meta() becomes its own round trip. Here is the real query log:

That is 201 queries versus 4 for the same 200 posts. The rule that falls out of it:
- Only need the IDs (deleting, re-saving, or fetching meta yourself in bulk):
fields => idsplusupdate_post_meta_cache => falseandupdate_post_term_cache => false. - Reading a meta value per row: leave meta cache priming on (the default). One bulk prime per batch beats one query per row. (The
te_bulk_apply()example above readspriceper row, which is why the harness callsupdate_meta_cache( 'post', $query->posts )once per batch:fields => idsnever primes meta on its own.)
no_found_rows => true is the free win in both cases: it drops the SELECT FOUND_ROWS() count that pagination needs and a bulk job does not.
Raise the memory limit last
When a single batch's legitimate working set still exceeds the CLI default, raise the limit for that one invocation rather than editing php.ini globally:
php -d memory_limit=512M "$(which wp)" eval-file te-bulk.phpBatch first. A higher limit only lets a naive -1 run survive a bigger table; batching means you never needed the headroom.
| Parameter | What it does | Use when |
|---|---|---|
posts_per_page => 500 + paged | Caps the working set per batch | Always, for bulk jobs |
fields => 'ids' | Returns IDs, not full objects | You don't need post bodies |
no_found_rows => true | Skips the total-row count query | Always, for bulk jobs |
update_post_meta_cache => false | Skips meta priming | You will not read meta |
update_post_term_cache => false | Skips term priming | You will not read terms |
WP_CLI\Utils\wp_clear_object_cache() | Resets object cache per batch | Inside every long loop |
To measure your own run, wrap the work in microtime(true) for wall time, read memory_get_peak_usage(true) for peak memory, compare get_num_queries() before and after, and define SAVEQUERIES to inspect the actual SQL in $wpdb->queries. That is how the numbers above were produced.
wp_insert_post memory fix for bulk imports
Imports are the write-heavy case where memory climbs fastest. wp_insert_post() was built for the admin "Add New Post" screen: one post per request, then the process exits. Loop it tens of thousands of times in one process and memory rises with every call, and raising memory_limit only moves the crash further down the file. The causes, roughly in order of impact:
- The object cache keeps every inserted post and its meta for the life of the process.
- Term counting: each category or tag assignment triggers a recount of that term.
- The
save_postecosystem: SEO, translation, search-index and custom plugins all listen onsave_postand friends, and each can hold state per insert. - Revisions, but only when the import updates existing posts (
wp_update_post(), orwp_insert_post()with anID): each update that changes the content can write a revision row. A fresh insert does not, because core's revision callback returns early when the save is not an update. - Comment counting, even on posts with no comments.
Each has an off switch. The batching and the per-batch wp_clear_object_cache() from the harness handle the first one; wrap the rest around the loop:
define( 'WP_IMPORTING', true ); // skips some pings and one-off side effects
add_filter( 'wp_revisions_to_keep', '__return_zero' ); // only matters if the import updates existing posts
wp_defer_term_counting( true );
wp_defer_comment_counting( true );
wp_suspend_cache_invalidation( true );
try {
foreach ( array_chunk( $rows, 200 ) as $batch ) {
foreach ( $batch as $row ) {
wp_insert_post( $row, true ); // $wp_error = true: a bad row returns WP_Error instead of halting
}
WP_CLI\Utils\wp_clear_object_cache();
gc_collect_cycles();
}
} finally {
wp_suspend_cache_invalidation( false );
wp_defer_term_counting( false ); // runs ONE recount now
wp_defer_comment_counting( false );
}The finally matters: if the script dies before wp_defer_term_counting( false ), term counts stay stale until something triggers a recount. Batches of 100 to 500 are the useful band; much smaller and the flush overhead dominates, much larger and heavy save_post listeners push memory back up.
Two cautions. Suspended invalidation means stale reads: if the import creates a parent post and then looks it up by slug to attach children, the lookup can read stale cache. Build a slug-to-ID map in PHP up front instead. And avoid wp_cache_flush() for this: on a site with a persistent object cache (Redis, Memcached) it empties the shared store for every visitor. That is why the harness uses wp_clear_object_cache(), which resets the in-process cache instead of flushing the store.
Strip the heavy save_post listeners
Most of the per-insert cost is third-party code. List what is hooked, then remove the expensive callbacks for the duration of the import and re-run their work once afterwards (for ElasticPress, a single wp elasticpress index --setup beats one Elasticsearch call per inserted post):
global $wp_filter;
$listeners = isset( $wp_filter['save_post'] ) ? array_keys( (array) $wp_filter['save_post']->callbacks ) : array();
WP_CLI::log( 'save_post priorities: ' . implode( ', ', $listeners ) );
// The nuclear option: nothing learns about the inserts until you restore it.
$saved_filter = $wp_filter['save_post'] ?? null;
unset( $wp_filter['save_post'] );
// ... import loop ...
if ( $saved_filter ) {
$wp_filter['save_post'] = $saved_filter;
}Bypass wp_insert_post with a multi-row $wpdb insert
When the data needs no hooks at all, one multi-row INSERT per batch avoids a round trip per row:
global $wpdb;
foreach ( array_chunk( $rows, 500 ) as $batch ) {
$values = array();
$placeholders = array();
foreach ( $batch as $row ) {
$placeholders[] = '(%s, %s, %s, %s, %d, %s, %s)';
array_push( $values, $row['title'], $row['content'], $row['excerpt'], $row['date'], $row['author_id'], $row['status'], $row['post_type'] );
}
$sql = "INSERT INTO {$wpdb->posts}
(post_title, post_content, post_excerpt, post_date, post_author, post_status, post_type)
VALUES " . implode( ',', $placeholders );
$wpdb->query( $wpdb->prepare( $sql, $values ) );
}What you give up: no GUIDs, no save_post (reindex search and caches yourself), no term relationships and no post meta (each needs its own batched inserts into wp_term_relationships and wp_postmeta). It is the right tool for raw data loads, not for content that plugins need to know about.
One more trap: wp post create in a shell loop does not leak, because every call is a fresh PHP process, but it pays the WordPress bootstrap on every post. Fine for a hundred posts; for tens of thousands, one wp eval-file with batched inserts is far faster.
Make it idempotent
A bulk run gets interrupted: someone closes the laptop, the SSH session drops, you Ctrl-C to check something. Write the per-row work so that running it twice changes nothing the second time. The te_bulk_apply above skips rows with no price and writes a derived value that is the same every run, so re-running after an interruption is safe. If your job is genuinely one-directional (incrementing a counter, appending to a log), guard it with a "done" flag in meta and skip rows that already carry it. The few minutes this costs to write back is cheaper than the afternoon you'll spend reconciling a half-applied run. For a production-grade version of this with a dry run, a backup gate, and a change-only changelog wrapped around the write, see safely bulk-updating custom fields.
Timing, so you know what you're dealing with
The microtime() bookends and the throughput line at the end are not decoration. The first time you run the harness against a real dataset, that number tells you whether the full job is a 10-second affair or a 40-minute one, which changes how you run it (inline, in a screen/tmux session, or as a scheduled job). Throughput also surfaces a slow te_bulk_apply: if you are doing 20 posts a second, something inside the loop is making a remote call or an unindexed query, and that is worth fixing before you point it at the whole table. For where the memory and query time actually go, see WP_Query performance and memory at scale above.
Add a custom WP-CLI command
wp eval-file is right for a one-off. When a bulk job becomes something you run again (a nightly backfill, a deploy step, a cron entry), give it a name: register it with WP_CLI::add_command() and it runs as wp te backfill with documented arguments, --help output and real exit codes. The smallest working version is a command name, a class, and one public method:
<?php
/**
* Plugin Name: TE CLI
* Plugin URI: https://techearl.com/wordpress-run-bulk-scripts-wp-cli
* Description: Example custom WP-CLI command with subcommands, args, flags, and a progress bar.
* Version: 1.0.0
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
* License: GPL-2.0-or-later
* Text Domain: te-cli
*/
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
class TE_CLI_Command {
/**
* Print a hello line.
*
* @when after_wp_load
*/
public function hello( $args, $assoc_args ) {
WP_CLI::success( 'Hello from the te command.' );
}
}
WP_CLI::add_command( 'te', 'TE_CLI_Command' );Three things make it work:
- The guard. The
WP_CLIclass only exists inside thewpbinary. CallingWP_CLI::add_command()on a web request would fatal the site, so bail out early (as above) or wrap the registration inif ( defined( 'WP_CLI' ) && WP_CLI ). WP-CLI sets the constant before it loads plugins, so the check is accurate by the time your file runs. - Public methods are subcommands. Pass a class and every public method becomes a subcommand of the top-level name, with underscores turned into hyphens: a
purge_cache()method iswp te purge-cache. If the class implements__invoke(), WP-CLI treats it as a single command and the other methods stop being subcommands. @when after_wp_loadtells WP-CLI to fully load WordPress first, which you want whenever the command touches posts, options or any core API.
Put it in a small plugin or an mu-plugin rather than a theme's functions.php, so it survives theme switches.
Arguments, flags and the OPTIONS block
Every subcommand method receives ( $args, $assoc_args ): positional arguments in order in $args, --key=value flags in $assoc_args. So wp te greet Ada --loud arrives as $args[0] === 'Ada' and $assoc_args['loud'] === true. Document them in the PHPDoc ## OPTIONS block and WP-CLI validates required arguments before your method runs and prints a real synopsis in wp help te greet:
/**
* Greet someone by name.
*
* ## OPTIONS
*
* <name>
* : The person to greet.
*
* [--loud]
* : Shout the greeting in uppercase.
*
* ## EXAMPLES
*
* wp te greet Ada --loud
*
* @when after_wp_load
*/
public function greet( $args, $assoc_args ) {
$message = "Hello, {$args[0]}.";
if ( ! empty( $assoc_args['loud'] ) ) {
$message = strtoupper( $message );
}
WP_CLI::line( $message );
}| Annotation | Meaning |
|---|---|
<name> | required positional argument |
[<name>] | optional positional argument |
<name>... | repeating positional (one or more) |
[--flag] | optional boolean flag |
[--key=<value>] | optional flag that takes a value |
The older one-line @synopsis: <name> [--loud] form still works, but the ## OPTIONS block is what the current handbook documents because it also feeds the per-argument descriptions.
Output helpers and exit codes
Do not echo from a command. WP_CLI::line() writes data to STDOUT, WP_CLI::log() is the same but silenced by --quiet, WP_CLI::success() prints a green Success: line, and WP_CLI::warning() prints a yellow warning to STDERR and keeps going. WP_CLI::error() is different: it prints a red Error: and halts the command with a non-zero exit code, which is what lets a wrapping shell script or CI job stop the pipeline. Use it for a precondition that makes the rest of the work pointless, such as a required plugin being inactive.
A progress bar for batch loops
For anything that loops over more than a handful of rows, WP_CLI\Utils\make_progress_bar( $message, $count, $interval = 100 ) renders a live bar with a percentage, elapsed time and an ETA. Call tick() once per item and finish() at the end:
public function backfill( $args, $assoc_args ) {
$post_ids = get_posts( array(
'post_type' => 'post',
'posts_per_page' => -1,
'fields' => 'ids',
) );
$count = count( $post_ids );
$progress = WP_CLI\Utils\make_progress_bar( 'Backfilling posts', $count );
foreach ( $post_ids as $post_id ) {
update_post_meta( $post_id, 'te_indexed', current_time( 'mysql' ) );
$progress->tick();
}
$progress->finish();
WP_CLI::success( "Backfilled {$count} posts." );
}Loading every ID with -1 is fine for a bounded set because each row is just an integer; for a table that keeps growing, use the paged loop from the harness and tick per row inside it. Outside a real WP-CLI context the helper returns a WP_CLI\NoOp object, so the tick() and finish() calls stay harmless.

Run wp te hello for the green success line, then wp help te to list the subcommands derived from your public methods and wp help te hello for the parsed description. If WP-CLI reports an unknown command, the plugin is not active, a fatal outside the guard stopped WordPress from booting, or the subcommand name does not match the method (hyphens, not underscores). The static sitemap generator is a full worked example of a custom command driven by a system cron.
Bulk process WordPress posts with AI
The same bulk machinery handles AI enrichment, and this is where the obvious approach costs the most. Say a directory site has 20,000 listing posts with half-empty fields (phone, website, bio). Looping over them and sending one synchronous model request per post works, but every call is a separate full-price request and you hit the rate limit long before you finish. The cheaper path is the provider's batch API: put every post into one asynchronous job, submit it, and collect the results later at half the token price. This is the WordPress-specific version of the LLM batch API guide; the flow is the same on Claude, OpenAI or Gemini.
Paging the database and batching the API are two different things, and you want both. The WP_Query still pages its reads so 20,000 rows never sit in memory, but the AI work goes out as one request to the batch endpoint carrying all 20,000 sub-requests, billed at 50% and returned within 24 hours.
Two commands: submit, then apply
Because the batch API is asynchronous, one command cannot submit and collect without blocking for up to a day. So the job is two commands: submit pages through the posts, builds the payload, posts it and stores the batch id in an option; apply, run later by hand or from cron, polls the batch and, once it has ended, matches each result back to its post by custom_id and writes the fields.

PHP has no official Anthropic SDK, so the example calls the REST endpoint with wp_remote_post. What you send the model (stripped text, selected blocks, ACF fields as context) is your own pre-processing; wp_strip_all_tags( $post->post_content ) is a reasonable default.
<?php
/**
* WP-CLI: te-listing-enrich submit
* Reads listings, submits ONE batch to the LLM, stores the batch id.
*/
if ( ! defined( 'TE_LLM_API_KEY' ) ) {
define( 'TE_LLM_API_KEY', getenv( 'ANTHROPIC_API_KEY' ) );
}
const TE_ENRICH_INSTRUCTIONS = 'You enrich business directory listings. '
. 'Given the listing text, return ONLY JSON: '
. '{"website": string|null, "phone": string|null, "summary": string}. '
. 'Use null when a value is not present. Do not invent data.';
/**
* Build one batch request for a single post.
* custom_id is the post ID, which is how we match the result back later.
*/
function te_build_request( $post ) {
$content = wp_strip_all_tags( $post->post_content ); // your pre-processing
return array(
'custom_id' => (string) $post->ID,
'params' => array(
'model' => 'claude-haiku-5-5', // cheapest tier that passes the task
'max_tokens' => 2048, // thinking counts toward this cap too
'system' => array(
array(
'type' => 'text',
'text' => TE_ENRICH_INSTRUCTIONS,
'cache_control' => array( 'type' => 'ephemeral', 'ttl' => '1h' ),
),
),
'messages' => array(
array( 'role' => 'user', 'content' => $content ),
),
),
);
}
function te_submit_command( $args, $assoc_args ) {
$batch_size = isset( $assoc_args['per-page'] ) ? (int) $assoc_args['per-page'] : 200;
$dry_run = isset( $assoc_args['dry-run'] );
$requests = array();
$paged = 1;
// Page the DB reads so we never load 20,000 posts at once.
do {
$query = new WP_Query( array(
'post_type' => 'listing',
'post_status' => 'publish',
'posts_per_page' => $batch_size,
'paged' => $paged,
// Only posts not already enriched: idempotency.
'meta_query' => array(
array( 'key' => '_te_enriched', 'compare' => 'NOT EXISTS' ),
),
) );
foreach ( $query->posts as $post ) {
$requests[] = te_build_request( $post );
}
$paged++;
} while ( $query->post_count > 0 );
WP_CLI::log( sprintf( 'Built %d requests.', count( $requests ) ) );
if ( empty( $requests ) ) {
WP_CLI::success( 'Nothing to enrich.' );
return;
}
if ( $dry_run ) {
WP_CLI::success( 'Dry run: not submitting.' );
return;
}
// ONE batch call carrying every request.
$response = wp_remote_post( 'https://api.anthropic.com/v1/messages/batches', array(
'timeout' => 60,
'headers' => array(
'x-api-key' => TE_LLM_API_KEY,
'anthropic-version' => '2023-06-01',
'content-type' => 'application/json',
),
'body' => wp_json_encode( array( 'requests' => $requests ) ),
) );
if ( is_wp_error( $response ) ) {
WP_CLI::error( $response->get_error_message() );
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$batch_id = $body['id'] ?? null;
if ( ! $batch_id ) {
WP_CLI::error( 'No batch id returned: ' . wp_remote_retrieve_body( $response ) );
}
update_option( 'te_pending_batch', $batch_id, false );
WP_CLI::success( "Submitted batch {$batch_id}. Run the apply command later." );
}
WP_CLI::add_command( 'te-listing-enrich submit', 'te_submit_command' );The apply command checks the batch status, streams the .jsonl results, and matches each line by custom_id (results come back in no particular order, so never match by position):
<?php
/**
* WP-CLI: te-listing-enrich apply
* Polls the pending batch; when done, writes results back to each post.
*/
function te_apply_command( $args, $assoc_args ) {
$batch_id = get_option( 'te_pending_batch' );
if ( ! $batch_id ) {
WP_CLI::error( 'No pending batch. Run the submit command first.' );
}
// 1. Check status.
$status = te_api_get( "https://api.anthropic.com/v1/messages/batches/{$batch_id}" );
if ( ( $status['processing_status'] ?? '' ) !== 'ended' ) {
WP_CLI::warning( 'Batch not finished yet. Try again later.' );
return;
}
// 2. Fetch the results (a .jsonl stream; one line per result).
$results_url = $status['results_url'];
$raw = wp_remote_retrieve_body( wp_remote_get( $results_url, array(
'timeout' => 120,
'headers' => array(
'x-api-key' => TE_LLM_API_KEY,
'anthropic-version' => '2023-06-01',
),
) ) );
$written = 0;
foreach ( explode( "\n", trim( $raw ) ) as $line ) {
if ( '' === $line ) {
continue;
}
$entry = json_decode( $line, true );
$post_id = (int) $entry['custom_id']; // match by id, NEVER by position
if ( ( $entry['result']['type'] ?? '' ) !== 'succeeded' ) {
WP_CLI::warning( "Post {$post_id} failed; leaving it for the next run." );
continue;
}
// Read the text block by type: a reply can open with a thinking block.
$text = '';
foreach ( $entry['result']['message']['content'] ?? array() as $block ) {
if ( 'text' === ( $block['type'] ?? '' ) ) {
$text = $block['text'] ?? '';
break;
}
}
$data = json_decode( $text, true );
if ( ! is_array( $data ) ) {
WP_CLI::warning( "Post {$post_id}: unparseable response, skipping." );
continue;
}
// Sanitize FIRST, then test the cleaned value, so a junk input
// (a disallowed URL scheme, "n/a") never writes an empty field.
// update_field() is ACF; use update_post_meta() without ACF.
$website = esc_url_raw( $data['website'] ?? '', array( 'http', 'https' ) );
$phone = sanitize_text_field( $data['phone'] ?? '' );
$summary = sanitize_text_field( $data['summary'] ?? '' );
if ( $website ) {
update_field( 'website', $website, $post_id );
}
if ( $phone ) {
update_field( 'phone', $phone, $post_id );
}
if ( $summary ) {
update_field( 'bio', $summary, $post_id );
}
update_post_meta( $post_id, '_te_enriched', current_time( 'mysql' ) );
$written++;
}
delete_option( 'te_pending_batch' );
WP_CLI::success( "Wrote {$written} listings." );
}
/** Small GET helper so the example does not repeat itself. */
function te_api_get( $url ) {
$response = wp_remote_get( $url, array(
'timeout' => 60,
'headers' => array(
'x-api-key' => TE_LLM_API_KEY,
'anthropic-version' => '2023-06-01',
),
) );
return is_wp_error( $response ) ? array() : json_decode( wp_remote_retrieve_body( $response ), true );
}
WP_CLI::add_command( 'te-listing-enrich apply', 'te_apply_command' );wp te-listing-enrich submit --per-page=200 --dry-run # see the count first
wp te-listing-enrich submit # actually submit
wp te-listing-enrich apply # later, once the batch has endedThe model output is untrusted text, so every write goes through a sanitizer (esc_url_raw restricted to http and https, sanitize_text_field for the rest), exactly like user input. The same idempotency rule as the harness applies: submit only selects posts without the _te_enriched meta and apply sets it only on success, so a crashed run resumes cleanly and a failed or unparseable result is retried on the next submit instead of lost or paid for twice. Without ACF, swap update_field() for update_post_meta(), or wp_update_post() if you are rewriting the body.
The apply phase is a natural fit for a WP-Cron event: keep a small queue of pending batch ids, and on each run return immediately if the queue is empty, otherwise ask the provider whether each batch has finished and write back the ones that have. The submit phase belongs in WP-CLI, not a web request, because paging 20,000 posts and talking to a remote API would tie up a PHP-FPM worker and trip a request timeout.
Cost, and picking the model
The model tier moves the bill more than batching does, and the two stack. For 20,000 listings at roughly 800 input and 200 output tokens each (pricing as of November 2026; check the provider pricing pages before a real run):
| Model | Synchronous | True batch (50% off) |
|---|---|---|
| Haiku 5.5 | ~$3.60 | ~$1.80 |
| Sonnet 5.5 | ~$72 | ~$36 |
| Opus 5.5 | ~$144 | ~$72 |
(Rates used: Haiku 5.5 $0.10 / $0.50, Sonnet 5.5 $2 / $10, Opus 5.5 $4 / $20 per million input / output tokens; the batch column halves both. The token counts are assumptions: the 5.5 models think by default and thinking tokens are billed as output, so check the usage on a small sample before you trust the estimate.)
Pulling a website and phone out of existing text is low-ambiguity work, so Haiku handles it; rewriting a bio with judgment is a Sonnet job; reconciling conflicting sources is where Opus earns its price (see Haiku vs Sonnet vs Opus). The cache_control marker in the example only caches once the shared prefix clears the model's minimum (512 tokens on Haiku 5.5, Sonnet 5.5 and Opus 5.5), so with this short instruction block it is a no-op; it pays off when every request carries a long rubric, taxonomy or style guide (see prompt caching and how to cut your AI API bill). Swapping providers is a field-name change, not a redesign: OpenAI uses POST /v1/batches with an uploaded JSONL file and Gemini uses batches.create. The same submit-and-apply shape also works for generating product images with Gemini Nano Banana, with one extra demand: dry-run the prompt on a few products first, because an off-target image across a whole catalog is a lot of wasted generation.
Where this leads
This harness is the engine under most of the bulk workflows on this site. Once you can reliably apply a function to every post from the command line, the only remaining question is where the data comes from. When it comes from a spreadsheet a non-developer maintains, the same loop reads the sheet with the Google Sheets API and writes each row with update_post_meta (or the WooCommerce CRUD), which is one half of syncing WordPress from a Google Sheet. And if your fields are managed by ACF rather than native meta, the read/write calls change (update_field in place of update_post_meta) but the harness does not, see ACF fields vs native post meta for which call to make.
wp eval runs a short PHP snippet passed as a string on the command line, good for a one-liner. wp eval-file runs a whole PHP file inside the same fully-loaded WordPress, which is what you want for anything longer than a single statement. Both execute in the global scope with WordPress already bootstrapped.php -d memory_limit=512M $(which wp) eval-file ... rather than editing php.ini globally.post_type to product (or your CPT) in the WP_Query args. For WooCommerce, do the actual write through the CRUD (wc_get_product(), the setters, then save()) instead of touching _price meta directly, so the product lookup tables stay consistent.$wpdb->queries accumulates every query when SAVEQUERIES is enabled. Over tens of thousands of iterations that climbs until PHP is killed. Calling WP_CLI\Utils\wp_clear_object_cache() each batch resets both, which is what keeps a large run flat.save_post listeners push memory back up. A raw multi-row $wpdb insert has no cache or hook overhead, so batches of 500 to 1000 are fine there.wp post create is its own PHP process, so nothing leaks, but every post pays the full WordPress bootstrap. For tens of thousands of posts, run one wp eval-file that calls wp_insert_post() in batches instead.get_post_meta() per row with the meta cache disabled, the per-row meta queries dwarf the saving. fields => ids is a win when you genuinely don't read meta or terms.WHERE post_id IN (...) query. Disabling that prime and then reading meta per row reintroduces the N+1.defined( 'WP_CLI' ) && WP_CLI guard (or an early return) so the registration is skipped on web requests. A theme's functions.php works too, but a small dedicated plugin survives theme switches and keeps the command in one obvious place.purge_cache() is wp te purge-cache. Run wp help te to see exactly what was registered.WP_CLI::warning() prints a yellow warning to STDERR and lets the command keep running. WP_CLI::error() prints a red error and halts with a non-zero exit code, which is what lets a wrapping shell script or CI job detect the failure and stop.wp_strip_all_tags( $post->post_content ) to send plain text; if block structure matters, use a block parser to extract just the parts you want. The batch flow itself does not care what the content looks like.Sources
Authoritative references this article was fact-checked against.
- wp_suspend_cache_invalidation(), WordPress Developer Referencedeveloper.wordpress.org
- wp eval-file - WP-CLI Command Referencedeveloper.wordpress.org
- Tips and best practices - WP-CLI Handbookmake.wordpress.org
- wp_suspend_cache_addition() - WordPress Developer Referencedeveloper.wordpress.org
- WP_Query - WordPress Developer Referencedeveloper.wordpress.org
- wp_cache_flush() - WordPress Developer Referencedeveloper.wordpress.org
- WP_Query performance parameters - WordPress Developer Referencedeveloper.wordpress.org
- get_post_meta() - WordPress Developer Referencedeveloper.wordpress.org
- WordPress object cache - WordPress Developer Referencedeveloper.wordpress.org
- WP_CLI\Utils\wp_clear_object_cache() - WP-CLI Handbookmake.wordpress.org
- Commands Cookbook: WP-CLI Handbookmake.wordpress.org
- WP_CLI::add_command(): WP-CLI Handbook internal APImake.wordpress.org
- WP_CLI\Utils\make_progress_bar(): WP-CLI Handbook internal APImake.wordpress.org
- Anthropic Message Batches documentationplatform.claude.com
- Anthropic pricingplatform.claude.com
- Claude models overview, Claude API documentationplatform.claude.com
- Anthropic prompt caching documentationplatform.claude.com
- Thinking, Claude API documentationplatform.claude.com
- WP-CLI command referencedeveloper.wordpress.org
- wp_insert_post() - WordPress Developer Referencedeveloper.wordpress.org
- wp_defer_term_counting() - WordPress Developer Referencedeveloper.wordpress.org
- wp_save_post_revision_on_insert(): WordPress Developer Referencedeveloper.wordpress.org





