Build an Autonomous Background AI Agent in WordPress with Action Scheduler (Zero Delay)
Running multi-step AI tasks inside a live WordPress request is a recipe for slow page loads, gateway timeouts, and fragile error handling. When a user publishes a post, places a WooCommerce order, or submits a form, they expect an immediate response—not a 20-second wait while an LLM reasons, calls tools, and verifies output.
By pairing Action Scheduler (as_enqueue_async_action()) with the WordPress AI Client (wp_ai_client_prompt()), you can dispatch an autonomous background agent with zero user-facing delay, chain reasoning steps cleanly across separate execution windows, and rely on built-in retries and job logs.
Zero-Delay Rule: Never block an interactive request on multi-step model reasoning. Persist run state, enqueue an async Action Scheduler job, return immediately, and let each background step chain the next until the goal completes.
| Stage | Mechanism | Why It Matters |
|---|---|---|
| 1. Trigger & Queue | as_enqueue_async_action() | Writes the job and dispatches an async runner on shutdown with zero UI delay |
| 2. Step Reasoning | wp_ai_client_prompt() | Calls configured providers server-side and returns structured next-tool decisions |
| 3. Tool Execution | Allowlisted WordPress actions | Applies bounded updates (meta, tags, drafts) and records step history |
| 4. Loop & Retry | Step chaining + exceptions | Chains the next step immediately or retries transient errors with full logs |
How Zero-Delay Step Chaining Works
Unlike standard scheduled cron tasks that wait for a future timestamp or visitor hit, as_enqueue_async_action() enqueues a one-time task to run as soon as possible and triggers Action Scheduler’s async request runner on shutdown. Instead of cramming an entire agent loop into one PHP process, each step reads saved run state, asks the model for the next tool call, executes an allowlisted action, and enqueues the next step until done is true or a step cap is reached.
- Predictable execution windows: Each LLM call and tool action runs in its own background invocation instead of compounding latency inside one request.
- Automatic retries on transient failures: Throwing a
RuntimeExceptionon network or provider errors lets Action Scheduler log the failure and retry cleanly. - Loop & budget guardrails: Enforcing a strict
MAX_STEPSlimit and idempotency check prevents runaway loops or duplicate post processing.
Background Agent Implementation (devnahian)
This example dispatches a background agent when a post is published, uses wp_ai_client_prompt() to pick structured tool calls, and chains steps asynchronously until finished:
<?php
final class DNTH_Autonomous_AI_Agent {
private const HOOK_STEP = 'dnth_ai_agent_execute_step';
private const GROUP = 'dnth-ai-agent';
private const MAX_STEPS = 5;
private const STATE_META_KEY = '_dnth_ai_agent_state';
public static function init(): void {
add_action( self::HOOK_STEP, array( __CLASS__, 'process_step' ), 10, 2 );
add_action( 'transition_post_status', array( __CLASS__, 'on_post_published' ), 10, 3 );
}
public static function on_post_published( string $new_status, string $old_status, WP_Post $post ): void {
if ( 'publish' !== $new_status || 'publish' === $old_status || 'post' !== $post->post_type ) {
return;
}
if ( get_post_meta( $post->ID, '_dnth_ai_agent_completed', true ) ) {
return;
}
self::dispatch( $post->ID, 'Generate an SEO summary and assign up to 3 relevant topic tags.' );
}
public static function dispatch( int $post_id, string $goal ) {
if ( ! function_exists( 'as_enqueue_async_action' ) ) {
return false;
}
$run_id = 'run_' . wp_generate_password( 10, false, false );
update_post_meta(
$post_id,
self::STATE_META_KEY,
array(
'run_id' => $run_id,
'status' => 'queued',
'goal' => sanitize_textarea_field( $goal ),
'step' => 1,
'history' => array(),
)
);
return as_enqueue_async_action(
self::HOOK_STEP,
array( 'post_id' => $post_id, 'run_id' => $run_id ),
self::GROUP,
true
);
}
public static function process_step( int $post_id, string $run_id ): void {
$post = get_post( $post_id );
$state = get_post_meta( $post_id, self::STATE_META_KEY, true );
if ( ! $post || ! is_array( $state ) || ( $state['run_id'] ?? '' ) !== $run_id ) {
return;
}
$step = (int) ( $state['step'] ?? 1 );
if ( $step > self::MAX_STEPS ) {
$state['status'] = 'stopped_max_steps';
update_post_meta( $post_id, self::STATE_META_KEY, $state );
return;
}
$decision = self::reason_next_action( $post, $state );
if ( is_wp_error( $decision ) ) {
throw new RuntimeException( esc_html( $decision->get_error_message() ) );
}
$result = self::execute_tool( $post_id, $decision );
$state['history'][] = array(
'step' => $step,
'tool' => $decision['tool'] ?? 'finish',
'result' => $result,
);
if ( ! empty( $decision['done'] ) || 'finish' === ( $decision['tool'] ?? '' ) ) {
$state['status'] = 'completed';
update_post_meta( $post_id, self::STATE_META_KEY, $state );
update_post_meta( $post_id, '_dnth_ai_agent_completed', 1 );
return;
}
$state['step'] = $step + 1;
update_post_meta( $post_id, self::STATE_META_KEY, $state );
as_enqueue_async_action(
self::HOOK_STEP,
array( 'post_id' => $post_id, 'run_id' => $run_id ),
self::GROUP
);
}
private static function reason_next_action( WP_Post $post, array $state ) {
if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
return new WP_Error( 'dnth_ai_missing', 'WordPress AI Client is not available.' );
}
$system = 'Return ONLY valid JSON: {"tool":"save_meta|assign_tags|finish","args":{},"done":boolean}';
$prompt = wp_json_encode(
array(
'goal' => $state['goal'],
'step' => $state['step'],
'title' => $post->post_title,
'body' => wp_trim_words( wp_strip_all_tags( $post->post_content ), 350 ),
'log' => $state['history'],
)
);
$raw = wp_ai_client_prompt( $prompt )
->using_system_instruction( $system )
->using_temperature( 0.2 )
->generate_text();
if ( is_wp_error( $raw ) ) {
return $raw;
}
$clean = preg_replace( '/^```(?:json)?\s*|\s*```$/m', '', trim( (string) $raw ) );
$parsed = json_decode( (string) $clean, true );
return is_array( $parsed ) && ! empty( $parsed['tool'] )
? $parsed
: new WP_Error( 'dnth_ai_bad_json', 'Invalid JSON decision.' );
}
private static function execute_tool( int $post_id, array $decision ): string {
$tool = sanitize_key( (string) ( $decision['tool'] ?? '' ) );
$args = is_array( $decision['args'] ?? null ) ? $decision['args'] : array();
if ( 'save_meta' === $tool && '_dnth_seo_summary' === sanitize_key( (string) ( $args['meta_key'] ?? '' ) ) ) {
update_post_meta( $post_id, '_dnth_seo_summary', sanitize_text_field( (string) ( $args['meta_value'] ?? '' ) ) );
return 'Saved _dnth_seo_summary';
}
if ( 'assign_tags' === $tool ) {
$tags = array_slice( array_filter( array_map( 'sanitize_text_field', (array) ( $args['tags'] ?? array() ) ) ), 0, 5 );
wp_set_post_tags( $post_id, $tags, true );
return 'Assigned tags: ' . implode( ', ', $tags );
}
return 'Finished run';
}
}
DNTH_Autonomous_AI_Agent::init();
Production Checklist
- Check provider availability gracefully: Always guard
wp_ai_client_prompt()calls and handleWP_Errorresponses when no provider or API key is configured. - Allowlist every tool and field: Restrict meta keys, post statuses, and taxonomies in PHP so the model cannot write arbitrary options or fields.
- Monitor Action Scheduler & loopback requests: Inspect runs under Tools > Scheduled Actions and ensure server firewalls do not block async loopback calls to
admin-ajax.php.
Quick FAQ
Does as_enqueue_async_action() run immediately without waiting for WP-Cron?
It queues the action right away and triggers Action Scheduler’s async queue runner on shutdown so background work starts promptly without blocking the user’s request.
What happens if the AI provider returns a rate-limit or network error?
When process_step() throws a RuntimeException on a WP_Error response, Action Scheduler records the failure in its log and retries the step automatically.