Skip to content
Arrow keys to move, Enter to open, Esc to closeAll results
AI · Guides

How to Edit WordPress With AI Coding Agents

A step-by-step tutorial for using Claude Code, Cursor and Codex-style agents on WordPress: setup, rules, small tasks, PHP review, and a safe path to production.

Written by
WPresident Editorial
Topic
AI

An AI coding agent can write a WordPress plugin faster than you can find the right hook in the developer reference. It can also write a plugin that works on the first click and carries a stored cross-site scripting hole, a form handler that anyone on the internet can call, or a query that runs three hundred times on every page view. At the moment you accept the diff, both versions look the same: the code runs, the page renders, the agent reports success. The distance between “it ran” and “it is right” is the subject of this tutorial.

Claude Code (a terminal-based agent), Cursor (an editor with an agent built in) and Codex-style tools (agents that work on a copy of your repository and hand back a patch) share one loop: read files, decide on a change, edit, run commands, read the output, try again. That loop is excellent when the answer can be found in public code and checked in seconds, and a lot of WordPress work fits: a template, a stylesheet, a hook, a shortcode, a WP-CLI script, a batch rewrite of titles. It is weak where correctness cannot be seen by running the code once. Who is allowed to call this function? What does it cost under real traffic? Does it survive the next WordPress release? The agent has no stake in those questions. You do.

The single most important idea is that the agent is not the control. Whatever protects your site has to sit outside the agent’s own judgement: a project where it can verify its work against something other than its own opinion, rules that are enforced and not merely requested, a review you perform in a fixed order, and a deployment path where a mistake lands on a staging copy and not on your visitors. This tutorial builds that frame in the order you would meet the problems.

You will start with the three ways an agent can touch a WordPress site, then sort tasks, learn the failure patterns that recur, set up a project the agent can verify itself in, and work in small tasks on a branch. Two sections cover reviewing generated PHP. The rest covers performance and caching, systems with their own markup rules, an account of driving a real site through an agent, and a deployment path that keeps production boring.

Here is what is first-hand and what is not. wpresident.com was built in November 2026 by Claude Code driving the site through NibWP, a WordPress plugin that exposes a site’s abilities to agents over the Model Context Protocol (MCP). NibWP is made by the publisher of WPresident, so read those parts as a builder’s account from the inside, not as an independent verdict. That build is the only hands-on material in this post, and it was page, template, component and small-plugin work done through an API, not a repository workflow in Cursor or in a Codex-style tool. Everything else comes from WordPress and tool documentation and from general practice, and it is written that way. We quote no benchmarks and no speed claims. File names, settings and limits differ between tools and change often, so check each vendor’s current documentation before you rely on one.

Key points

  • The danger is not agent code that fails, it is agent code that works while skipping escaping, authorization and performance.
  • Where the agent is plugged in decides the undo path: files in git, content in a database, or code running on a live server.
  • Small tasks with a written acceptance test, a plan before edits and one branch per task beat long, open-ended prompts.
  • A rules file records your standards but is only advice, so enforce the important ones with permissions, static analysis and tests.
  • Review generated PHP in a fixed order, from who can call it to how its output is escaped.
  • Caches and framework validators can hide the truth, so verify with a cache bypass, a dry run and a read-back of what was actually stored.
  • Ship through staging with a backup and a rollback path, and keep powerful abilities such as arbitrary PHP execution away from production.

Three ways an agent touches WordPress, and why the undo path differs

“Agent” names a loop, not a place. What matters for safety is the wire that loop is plugged into, because the wire decides what a mistake costs and how you take it back. There are three attachment points, and most people end up using all of them.

The first is the repository. The agent opens a folder on your machine, such as a theme, a single plugin or a must-use plugin, and edits files. Claude Code, Cursor and Codex-style tools all do this. Every change is a diff, git restores any file in one command, and nothing touches a database unless you let the agent run code against a local site, which is disposable. This is where you should learn.

The second is site tools. The agent talks to a running WordPress site through the REST API with an application password, WP-CLI over SSH, or an MCP server that publishes a menu of abilities such as create a post, update an option or write a file. Most current agents can connect to MCP servers; check each tool’s setup. The changes land in the database and in files on a live or staging site, and git does not see them. This is how wpresident.com was built, with Claude Code working through NibWP, and the undo path has to be designed before the first call, not after the first surprise.

The third is a shell on a server: the agent runs commands over SSH or in a hosting terminal. It is the most capable mode and the least forgiving, because one wrong command can delete a directory or rewrite a table with no review step in between. Most WordPress work does not need it. If you grant it, grant it on staging, as a user that cannot read production credentials.

Move down the stack only when the work cannot be done higher up. If a task can be a change to files in git, do it there and ship the files through your normal path, and reserve site tools for what lives in the database, such as content, menus and options. Whatever the wire, ask what the worst thing this credential can do is, and how you would reverse it.

The credential is the real boundary. An application password carries the capabilities of the user it belongs to, so an agent connected as an administrator can do whatever an administrator can, including installing plugins and editing code. Create a dedicated user with the smallest role that covers the job, such as an editor for content work, and revoke the application password when the task ends.

Blast radius of an agent connection, safest layer first

Files in a local repositoryGit shows every change and restores any file.
A staging site through site toolsDisposable, but take a backup first.
Content and options on the live siteDatabase changes git cannot see; undo needs a backup.
PHP that executes on the live siteOne mistake can take the front end down.
Server shell, credentials and secretsReach the agent should not have.
The lower the layer, the harder a mistake is to see and to reverse, so work as high in this stack as the task allows.

What to hand over, what to supervise and what to keep

Agents are not good or bad at “WordPress” as a whole. They are good at tasks that have three properties: plenty of public examples, a clear stop condition and a check you can run in seconds. The more of those a task has, the more you can delegate. The fewer it has, the more you must supervise.

What fits well: templates and block theme markup, because the result is visible on one page load; CSS, because mistakes show instantly and cost nothing to revert; small plugins with a narrow job, such as a shortcode, a custom post type or a settings screen; bulk content work done through a script, such as rewriting hundreds of product short descriptions from a spreadsheet or drafting missing alt text for a human to approve; WP-CLI scripts and one-off migrations; and tests, refactors and plain explanations of an unfamiliar plugin.

What fits badly: anything where failure is invisible when you click through, such as authentication, authorization, payments, personal data, file uploads and anything that decides who sees what; performance under real traffic, because the agent sees ten test posts and not ten thousand; and anything that reaches across many systems at once, such as a checkout customization touching a payment gateway, tax settings, emails and stock levels. In those areas the agent can still draft pieces and explain options, but the design and final review stay with you.

A concrete scenario, offered as an illustration and not as data: a WooCommerce store with 800 products on a shared plan. Asking an agent for a WP-CLI script that reads a spreadsheet export and updates product short descriptions is a good delegation. You can check the result by sampling, you can run the script first on a copy, and a database export gives you the way back. Asking the same agent to rewrite how discounts are calculated at checkout is supervision territory at best. The logic is subtle, a mistake is silent, and real money moves. Same agent, very different risk profile.

Decide before you prompt. The question is not “can the agent do this?”, because it can try almost anything. The question is “how would I find out if it got this wrong, and how fast?” If the honest answer is “a visitor would tell me”, the task is not ready to be delegated, and the figure shows what to do instead.

Delegate, supervise or keep

What does the change touch?
Presentation only: CSS, template markup, copyDelegate. Review the diff and check the page at two widths.
Behaviour in code: a hook, a shortcode, a small plugin featureSupervise. Plan first, run the static checks, then review in the fixed order.
Bulk changes to content or optionsDry run on staging, take a backup, compare a sample by hand, then run it in full.
Logins, payments, personal data or file uploadsKeep the design yourself, let the agent draft pieces, and review every line twice.
Sort every task by how quickly you would notice a mistake, not by how hard the task looks.

Where agents go wrong on WordPress, and which mistakes announce themselves

The mistakes agents make on WordPress follow a pattern, and the pattern is more useful than a list of bugs. Mistakes that announce themselves, such as a fatal error or a collapsed layout, get fixed in minutes, by you or by the agent reading the error. The dangerous ones stay quiet. The figure places typical mistakes on that spectrum. The positions are editorial judgement, not measurements.

Stale and invented APIs come first. Models learn WordPress from years of public code, so they reproduce old habits: query_posts() in a template, get_page_by_title() (deprecated in favour of a WP_Query lookup), classic template parts inside a block theme. Now and then they invent a function that merely sounds right. A function that does not exist is the friendly case, because PHP throws a fatal error you can see. Deprecated code that works today and breaks in a later release is the unfriendly case. Check any unfamiliar function against the developer reference, or ask WordPress itself:

$ wp eval 'var_dump( function_exists( "function_name_to_check" ) );'
$ grep -rn "function function_name_to_check" wp-includes wp-admin

Turn on debug logging as well, because deprecation notices land in the log and tell you what the agent just used.

Security by omission is next. The agent writes the handler that does the job and leaves out the guards that do not change the happy path: a capability check, a nonce, sanitization, escaping, prepared statements. The code works perfectly when you test it as yourself with friendly input. Two sections of this tutorial are devoted to reviewing exactly this.

Then performance blindness. The agent tests with a handful of posts, so a query inside a loop or an unbounded query looks fine until the data grows.

A weak model of WordPress’s moving parts follows: hook timing, page caching (the change is live but the cached copy still serves the old page), plugin interactions, PHP version differences and multisite. Reading code does not reveal runtime state, so put those facts in the rules file and let the agent run commands to find out.

Finally, confident reporting. An agent may say the checks passed when it never ran them, or quietly edit a test until it passes. The cure is mechanical: ask for the pasted output of every command, and read the diff of the tests as carefully as the diff of the code.

How loudly each kind of mistake fails

How to read this: each row is one option, and its dot shows where it sits between Fails loudly, found at once and Fails silently, found late. Placement is an editorial judgement, not a measurement.

  1. 1Broken layout or CSSVisible in one page load.
  2. 2PHP fatal errorWhite screen or a line in the log.
  3. 3Wrong data in a templateVisible only if you open the right page.
  4. 4Slow query or query in a loopFine with ten posts, painful with ten thousand.
  5. 5Missing capability check or nonceWorks for you; nobody notices until someone abuses it.
  6. 6Unescaped stored outputLooks correct on screen while the hole stays open.
Editorial placement, not measurement: the quieter a mistake is, the more your review has to look for it deliberately.

Build a project the agent can verify itself in

An agent that can check its own work is worth more than a smarter agent that cannot. Verification means commands that return pass or fail, and a log that shows errors, so that “done” becomes a claim backed by output. Build that before the first real task.

Start with a local site you can break. A desktop local-development app works, so does a Docker setup, and so does the official WordPress environment tool run through Node, which starts a disposable site from a small config file kept in the repository. What matters is that the site is local, runs the same PHP major version as production, and lets the agent run WP-CLI against it. Seed it with an anonymized export of production so the data volumes are not fantasy.

Decide what goes into git. The cleanest choice is a repository that contains only your theme or plugin folder, so the agent cannot wander into core files. If you must version the whole site, ignore core, uploads, caches, wp-config.php and database dumps.

Turn on logging so errors have somewhere to go. Display stays off because printed errors corrupt JSON and AJAX responses and leak file paths:

$ wp config set WP_DEBUG true --raw
$ wp config set WP_DEBUG_LOG true --raw
$ wp config set WP_DEBUG_DISPLAY false --raw

Now add checks, cheapest first. A syntax check with php -l costs nothing and catches the typo that would otherwise white-screen the site. PHP_CodeSniffer with the WordPress Coding Standards flags many security omissions by name: unescaped output, unverified nonces, unsanitized input, concatenated SQL. Install it as a development dependency and point it at your code:

$ composer require --dev wp-coding-standards/wpcs dealerdirect/phpcodesniffer-composer-installer
$ vendor/bin/phpcs --standard=WordPress wp-content/plugins/acme-extras

Static analysis with PHPStan and a WordPress extension finds calls to functions that do not exist, which is the invented-API problem. Unit tests can be scaffolded with the wp scaffold plugin-tests command, and Query Monitor on the local site shows the queries, hooks and remote requests for each page.

Two cautions. Passing the sniffs does not mean the code is secure, because tools match patterns and cannot see intent. And agents learn quickly that a comment such as phpcs:ignore silences a warning, so search every diff for suppression comments and ask why each one exists.

Write the rules file that carries your WordPress standards

Every session begins with an agent that knows WordPress in general and your project not at all. A rules file is the briefing it reads first. Claude Code reads a file named CLAUDE.md in the project, Cursor stores project rules alongside the code, and Codex-style tools commonly read AGENTS.md, a convention several tools now share. Names and locations change, so confirm them in each tool’s documentation.

Write down the facts the agent cannot infer: WordPress and PHP versions, whether the theme is a block theme (so there is no header.php to edit), your prefix and text domain, where the debug log lives and which commands verify work. Then the protective rules, the boundaries and the definition of done. A small example:

# Project rules: acme-extras plugin

## Environment
- WordPress 6.x, PHP 8.1 minimum, block theme (no classic template files)
- Prefix acme_ for functions, hooks and options. Text domain: acme-extras
- Local site runs in wp-env. Debug log: wp-content/debug.log

## Security rules (non-negotiable)
- Every state-changing handler checks a capability AND a nonce.
- Unslash and sanitize all input. Escape all output where it is printed.
- Database access only through $wpdb->prepare() or WP_Query.
- REST routes always set a real permission_callback.

## Verify before you say done
1. php -l on every changed file
2. vendor/bin/phpcs --standard=WordPress on changed files
3. Load the affected page and confirm the debug log is clean
4. Paste the output of each command in your reply

## Boundaries
- Never edit WordPress core, wp-config.php or other plugins.
- Never run SQL directly. Use WP-CLI or WordPress functions.
- Ask before adding a dependency, a custom table or a scheduled event.

Every line should have earned its place through a mistake you have seen or one you cannot afford. Keep rules short, imperative and checkable, delete rules the agent already follows, and point at one file in your repository that shows the standard pattern, such as your form handler, instead of pasting documentation.

A rules file is advice, nothing more. The agent can ignore it, forget it in a long session or lose it when context is trimmed. So enforce what matters somewhere the agent cannot negotiate: the tool’s permission settings (deny reading wp-config.php or running destructive commands), its ignore mechanism so secrets never enter the context (check the documentation), phpcs and tests in a git hook or CI job, a protected main branch, and a user with narrow rights on every live connection. Rules say what you want; mechanisms stop what you cannot afford.

Treat the file as a ratchet: after any incident, add one line to the rules and, where possible, one automated check. We have no controlled comparison of rules files with and without, so take the structure and size here as practical advice, not a finding.

Work in small tasks: a plan first, one branch, one commit

The biggest lever you control is task size. Agents handle one clear change well and drift on open-ended ones, and you can only review so many lines with care. A diff of forty lines gets read. A diff of nine hundred lines gets skimmed and approved. Size the task to your review: one behaviour, one acceptance test, a handful of files.

Write the brief with four parts: the goal, which files may change, the constraints from the rules file and the acceptance test. For example:

Goal: add a shortcode named acme_team that lists posts of the type team_member.
Files: only wp-content/plugins/acme-extras/includes/shortcodes.php and a new test file.
Constraints: follow the rules file. Use WP_Query with no_found_rows. Escape on output.
Acceptance: the shortcode renders three cards on the Team page, the debug log stays clean, phpcs passes.
First reply with a plan and the list of files you will touch. Do not edit yet.

Ask for a plan before any edit. Many agents have a dedicated planning mode, and where yours does not, the last line of the brief does the same job. The plan is the cheapest review you will ever do. A wrong file, a new dependency, a custom database table or a feature you never asked for is visible in ten lines and free to correct, and expensive to unpick after a hundred lines of code exist.

Work on one branch per task and commit once per task, so the history is a list of reversible units:

$ git switch -c task/team-shortcode
$ git diff --stat
$ git add wp-content/plugins/acme-extras
$ git commit -m "Add acme_team shortcode"

If task four breaks something, you revert task four and keep the rest. The diff stat is also a quick sanity check: if a task meant to touch one file shows eleven, stop and ask why before you read a single line.

Plan for drift. If the agent fails the same check three times, stop it. Read the error yourself, narrow the task, or begin a fresh session with a short note of what you learned, because long sessions accumulate stale assumptions. Watch for fixes that make red go away without solving anything: an edited test, a deleted check, an added suppression comment, an exception that is caught and swallowed.

Finally, name the end of the task and respect it. “While you are here, also tidy the settings page” is how a forty-line diff becomes four hundred lines. Put the idea on a list for the next task.

The loop for one task

  1. Write the briefGoal, files, constraints, acceptance test.
  2. Ask for a planNo edits yet; the plan lists the files it will touch.
  3. Correct the planCut anything you did not ask for.
  4. Implement on a branchOne branch per task so a revert is one command.
  5. Run the checksLint, standards, tests and the debug log.
  6. Review the diffRead code and tests; search for suppression comments.
  7. Commit and resetOne commit per task, then a fresh session.
A plan before edits and a commit after review turn a long agent session into small, reversible steps.

Review generated PHP, part one: who may call this code, and did they mean to

Review generated PHP in the same fixed order every time. The order in the figure starts with the question agents skip most. It is not “does this work?” but “who can reach this?”

First find every entry point. In a diff, search for the hooks that accept requests: admin_post_ and admin_post_nopriv_ actions, wp_ajax_ and wp_ajax_nopriv_ actions, register_rest_route calls, shortcodes that take attributes, and any code that reads the request superglobals during init. The nopriv variants make a handler reachable by logged-out visitors. Agents add them “so it also works in a private window” while testing. Unless the feature is genuinely public, delete them.

Then check authorization. A capability check answers “may this user do this?” through current_user_can(). Choose the narrowest capability that fits, and prefer an object-level check: current_user_can( ‘edit_post’, $post_id ) asks about this particular post, while a generic edit_posts check does not. An agent that tests is_user_logged_in() has written a login check, not an authorization check.

Then check intent. A nonce answers “did this request come from a form or link that WordPress issued to this user for this action?” It defends against cross-site request forgery. It is not authorization: any logged-in user can obtain a valid nonce, so a nonce without a capability check lets every subscriber run the action, and generated code very often has one guard without the other. Use wp_nonce_field() and check_admin_referer() for forms, check_ajax_referer() for AJAX, and the X-WP-Nonce header for REST requests made with cookie authentication.

REST routes have a third place to look. Authorization lives in the permission_callback, and since WordPress 5.5 leaving it out triggers a notice. The quick fix for the notice is a callback that returns true for everyone, which makes the route public. That is fine for data you would publish anyway. For everything else the callback must call current_user_can().

Here is a handler that passes all of this. It registers no nopriv hook, so a logged-out request never reaches it, it ties the capability to the specific post, and it checks the value against an allowlist and not merely cleans it. The matching form posts to admin-post.php with a hidden field named action set to acme_save_priority, plus wp_nonce_field( ‘acme_save_priority’, ‘acme_nonce’ ):

add_action( 'admin_post_acme_save_priority', 'acme_handle_save_priority' );

function acme_handle_save_priority() {
	check_admin_referer( 'acme_save_priority', 'acme_nonce' );

	$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
	if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
		wp_die( esc_html__( 'You are not allowed to do this.', 'acme-extras' ), '', array( 'response' => 403 ) );
	}

	$allowed  = array( 'low', 'normal', 'high' );
	$priority = isset( $_POST['priority'] ) ? sanitize_key( wp_unslash( $_POST['priority'] ) ) : '';
	if ( ! in_array( $priority, $allowed, true ) ) {
		wp_die( esc_html__( 'Invalid priority.', 'acme-extras' ), '', array( 'response' => 400 ) );
	}

	update_post_meta( $post_id, 'acme_priority', $priority );

	wp_safe_redirect( add_query_arg( 'acme_saved', '1', get_edit_post_link( $post_id, 'raw' ) ) );
	exit;
}

Review order for a PHP diff

  1. Find entry pointsHooks, AJAX, admin-post, REST routes, shortcodes.
  2. Check authorizationA narrow capability, tied to the object.
  3. Check intentA nonce; never a substitute for the capability.
  4. Check inputUnslash, sanitize, then validate against what is allowed.
  5. Check storagePrepared statements, WP_Query or the meta APIs.
  6. Check outputEscape late, with the function that matches the context.
  7. Check side effectsCron events, remote calls, writes on page views.
Walk every generated change through the same seven questions, starting with who can reach the code.

Review generated PHP, part two: input, queries and output

Three rules cover most of what is left: sanitize and validate on the way in, use prepared statements or WP_Query on the way to the database, and escape on the way out, at the moment of printing. Agents usually do the first, sometimes the second and often skip the third, because output escaping never changes how a page looks during a test.

Input first. WordPress adds slashes to the request superglobals, so call wp_unslash() before you sanitize, then use a sanitizer that matches the type: sanitize_text_field() for a line of text, sanitize_textarea_field() for several lines, sanitize_email(), absint() for IDs and sanitize_key() for slugs. Sanitizing is not validating: if a field must be one of three values, compare it against an allowlist with in_array() in strict mode.

Queries next. Agents love to build SQL by concatenation, because it is the shortest path to a working demo and the code is already in their memory from outside WordPress:

$rows = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value = '" . $_GET['ref'] . "'" );

That is injectable. The corrected version sanitizes the input and hands the value to prepare(), with a placeholder for each value:

$ref  = isset( $_GET['ref'] ) ? sanitize_text_field( wp_unslash( $_GET['ref'] ) ) : '';
$rows = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s",
		'acme_ref',
		$ref
	)
);

Use the placeholders %s, %d and %f for values, and wrap any text destined for a LIKE pattern in $wpdb->esc_like() first. Often the better answer is no hand-written SQL at all: WP_Query with a meta_query, or get_posts(), does the same job with the escaping done for you. Put that preference in the rules file.

Output is where the figure helps: escape where the value is printed, with the function for the place it lands. Common agent errors are an attribute escaped as HTML text, a link printed without esc_url(), stored post HTML echoed without wp_kses_post(), and JSON placed in an inline script through plain PHP encoding. Also escape once: escaping before storage and again on output produces garbled entities, and we saw a version of exactly that with Etch, described later.

printf(
	'<a href="%s">%s</a>',
	esc_url( $url ),
	esc_html( $title )
);

One last pass for the places where user data sneaks in sideways: file uploads (use the WordPress upload handler and clean the file name), unserialize() on anything a visitor can influence (use JSON), remote requests to user-supplied addresses (use the safe remote functions), eval or include with a dynamic path, and secrets pasted into code.

Match the escape to the destination

Where the value ends upEscape or prepare with
Text inside an HTML elementA title or name printed in markupesc_html()
An HTML attributeA class, title or data attributeesc_attr()
A link or image addressAn href or src valueesc_url()
A URL you saveStored in the database or an optionesc_url_raw()
HTML you choose to allowStored post content or rich textwp_kses_post() or wp_kses()
Data for JavaScriptA value placed in a scriptwp_json_encode() or wp_add_inline_script()
A value inside SQLA search term or ID in a query$wpdb->prepare() placeholders
Escaping is chosen by where the value lands, so one generic function applied everywhere is a sign of a mistake.

Performance, caching and the checks that reading code cannot do

Agents optimize for correct output, not for cost per request, and reading a diff will not tell you how many queries a page runs.

These patterns recur in generated code and are worth scanning for:

  • An unbounded query: posts_per_page set to minus one on a site that will keep growing.
  • A WP_Query or get_posts call inside a loop, so the database is asked once per item instead of once per page.
  • A meta_query that filters on meta values. The meta_value column in the standard postmeta table is not indexed, so this gets slow on large sites.
  • A remote HTTP request on every page render, with no short timeout and no cached result.

Two small habits fix most of the first four: bound every query with posts_per_page and add no_found_rows when you do not paginate, and cache anything fetched from outside with a short timeout and a transient, as below:

function acme_get_rates( $endpoint ) {
	$rates = get_transient( 'acme_rates' );
	if ( false === $rates ) {
		$response = wp_remote_get( $endpoint, array( 'timeout' => 5 ) );
		if ( is_wp_error( $response ) ) {
			return array();
		}
		$rates = json_decode( wp_remote_retrieve_body( $response ), true );
		set_transient( 'acme_rates', $rates, 15 * MINUTE_IN_SECONDS );
	}
	return $rates;
}

Measure on the local site with Query Monitor, which lists each page’s queries, the function or plugin behind them, duplicates, slow queries, outgoing HTTP calls and hooks. You read that panel yourself, since the agent cannot see your browser.

Then there is the cache trap. You change a template, reload and see the old page while the agent insists it is done. A page cache may simply be answering. On this site, xSpeed Cache 1.4.8 added an x-xspeed-cache header that read MISS on a first request and HIT (nginx) on a repeat. A request carrying an unknown query string bypassed the cache and always returned MISS, which made it a handy way to see what an uncached request looks like, and HEAD requests bypassed it as well. We have no timings to quote, though uncached pages were noticeably slower than cached ones when the server was busy. Header names differ between cache plugins, so look at yours:

$ curl -s -D - -o /dev/null "$PAGE_URL" | grep -i x-xspeed-cache
$ curl -s -D - -o /dev/null "$PAGE_URL?wprnc=$RANDOM" | grep -i x-xspeed-cache

We never needed to purge by hand during the build and cannot say the plugin’s purge rules are complete. Where we wrote our own admin screens with ACF PRO, we hooked acf/save_post to purge the page cache. Whenever agent code changes what a page prints, ask which cache holds the old copy and who clears it.

When the system has its own rules: Etch, block markup and validators

Some WordPress work is not PHP at all. Page builders and block systems store content in a structure with strict rules, and an agent that improvises produces markup that renders wrongly or not at all. Give the agent the system’s data model and a validator, not a description of what you want.

Here is what we learned with Etch 1.8.3, which we drove through NibWP’s API and never through the visual canvas, so we say nothing about the canvas experience. Content is stored as blocks in post_content: etch/element, etch/text, etch/component, etch/loop, etch/condition and others. Classes carry their CSS as separate style entities, with a global stylesheet kept in an option, and CSS nesting worked. A shared header and footer are components stored as wp_block posts that pages reference. Loops use named presets stored in an option, with parameters that accept defaults. The output markup was clean, with no wrapper elements we had not authored.

Validation is what made this workable. NibWP’s Etch converter takes a payload of blocks plus styles and has a dry_run flag that checks everything without writing. Its rules read like a house style: class names must be BEM-like with a brand prefix, colors must be tokens with a fallback, font sizes must use a token style, and every element needs a class. A hard-coded hex was flagged, an rgba() inside a var() fallback failed, and clamp() or complex min() fallbacks for font sizes were rejected. We wrote every token with a fallback so a page still renders if the framework’s output goes missing. An illustration with Automatic.css tokens:

.acme-card {
	background: var(--base, #ffffff);
	color: var(--neutral-ultra-dark, #1a1a1a);
	border-top: 4px solid var(--primary, #5B21B6);
	font-size: var(--text-m, 1rem);
}

Three lessons carry beyond Etch. First, copy the validator’s rules into your rules file, so the agent complies on the first attempt and does not learn them one rejection at a time. Second, a noisy validator gets ignored. The converter produced 89 “orchestration suggestions” on one page and we found no way to silence them. A validator that talks that much trains you to skim, so read the list of passed and failed checks first. Third, the usual security advice has an exception: Etch escapes text content itself, so escaping it beforehand produced double-encoded entities such as &amp;. “Escape late” assumes you own the output.

One rendering detail cost us time: styles are registered while blocks render and printed late in wp_head, so in our custom canvas we had to render the content before wp_head or the page styles went missing. Let the system’s converter generate markup, and let the agent supply content and intent.

etchwp.com
The Etch website homepage with the headline One Builder. Multiple Platforms. Unlimited Possibilities. above a preview of its editor.
Etch stores pages as structured blocks, which is why an agent needs its validator and data model and cannot simply improvise markup.

A builder’s account: driving a whole site through NibWP

This part is the first-hand core of the post, with the caveat from the introduction: NibWP is a product of WPresident’s publisher, so this is a builder’s account from the inside, not an independent verdict. NibWP 2.0.0 is a WordPress plugin that exposes a site’s abilities over MCP. The endpoint has the form /wp-json/mcp/nibwp, speaks JSON-RPC, and authenticates with a WordPress application password.

The agent sees only three generic tools: discover abilities, get an ability’s schema and execute an ability with parameters. In practice the ability schemas were the documentation we relied on, so a schema that names its parameters precisely is worth more than any prose guide. The abilities we used were post create, update and get, meta and option reads and writes, file tools (write, read, list, delete, disable), execute-php, a preflight skill that issues a token, the Etch HTML-to-component converter, Automatic.css variable tools and Slim SEO meta-tag tools for posts and the home page. The preflight token is tied to the target post and a push mode (we used replace_section), which is the kind of scoping you should look for in any tool that writes: a token for one post and one mode cannot quietly rewrite something else.

The scale of the job is worth stating. Claude Code produced about 45 pages, a single-post template, shared header and footer components, SEO titles and descriptions, a color palette with typography settings and several sandbox plugins, driven from scripts, without opening wp-admin for page building. A full page push took roughly 10 to 30 seconds, long enough that you want it automated. Everything above ran through the same three generic tools.

The safety lesson is the one to remember. The execute-php ability runs arbitrary PHP. It is powerful, and it is risky, and the site owner told us to stop using it. We finished the build with the narrower abilities and the sandbox files. If you try a tool like this, work on staging, connect as a dedicated least-privilege user, keep backups, and read what the agent plans to run before it runs. A narrow ability list is a feature, not a limitation.

nibwp.com
The NibWP website homepage with the headline Connect WordPress. Speak to agents. and a preview of its WordPress admin screen.
NibWP exposes the abilities of a site to an agent over MCP, and it is made by the publisher of WPresident, so treat this account as an insider view.

The incidents, and what each one teaches

The most useful part of a hands-on account is what went wrong. Four incidents from the build each map to a lesson for any agent workflow.

The first was loud and contained. NibWP writes PHP files only under wp-content/nibwp-sandbox/, where they load as single-file plugins. A stray apostrophe inside a PHP string in one of them caused a fatal error, which tripped crash safe mode: a .crashed marker that disables every sandbox plugin. The custom front-end canvas disappeared until we fixed the file and deleted the marker. The safety net did what it exists to do: it disabled the sandbox plugins instead of leaving a broken file loading on every request. It also showed the value of a syntax check before a file ever reaches a live site, which is the php -l step from the verification ladder.

The second was quiet and expensive. The converter’s save step treated a dollar sign followed by digits as a back-reference, so text such as a price was stored as just 0. Every price on the Advertise page was lost until we noticed. The workaround was to put the dollar sign in its own text block. The lesson is to read back what was stored after a bulk push and search for expected strings, such as every price, because a success response from a write tool describes the call and not necessarily the content.

The third came from a plugin setting, not the agent. Slim SEO’s option to remove the category base made /ai/ resolve as a category archive instead of our /ai/ page. We turned the option off and flushed rewrites. A rewrite conflict does not show up in the code you read, so after enabling any option that touches URLs, load the affected addresses and check what answers.

The fourth was infrastructure. MCP calls need a session id from initialize, and sessions expired now and then (“Session not found”, “Missing Mcp-Session-Id”), so we re-initialized and at times used a small script client instead of the chat client’s built-in connector. When the host struggled, calls timed out and one run returned “Error establishing a database connection”. That was a host problem, but it shaped the workflow: we added retries. Any agent job that writes should be safe to repeat.

Four incidents from the build

What we sawCauseWhat we did
Front end vanishedThe custom canvas disappearedApostrophe in a PHP string; crash safe mode trippedFixed the file, deleted the .crashed marker
Prices lostText came out as 0Save step read a dollar sign plus digits as a back-referencePut the dollar sign in its own text block
Wrong page at a URL/ai/ showed a category archiveSlim SEO option removed the category baseTurned it off and flushed rewrites
Failed callsSession and database errorsExpired sessions and a struggling hostRe-initialized and added retries
Each incident had a different cause and a different lesson, and the quiet one cost the most.

A safe path from agent output to production

The aim of a deployment path is to make production the last place a mistake can appear, and to make leaving it a single step.

Run the change on a staging copy first. It should match production in PHP version, WordPress version and plugin versions, and carry a recent copy of the data, anonymized if it holds personal data. Click the paths that matter: log in, submit a form, search, open a post with comments, and on a store add a product to the cart and reach checkout. Read the debug log afterwards and look at Query Monitor on the pages the change touched.

Deploy by a route that a human triggers: a git pull on the server, a CI job or an upload of the changed files. Do not give the agent the production SSH key or administrator credentials. Ask it to prepare the release instead: a commit, a short changelog, the list of changed files and a list of any database changes. You then press the button.

Treat database changes as versioned code. If a feature needs a new option or table, ship an upgrade routine that compares a stored version number with the code’s version, runs once and is safe to run twice, and record an option’s old value before you overwrite it.

Take a backup immediately before the release and know your rollback:

$ wp db export before-release.sql
$ wp plugin deactivate acme-extras
$ wp cache flush
$ wp rewrite flush

The first line is the safety copy. The second switches the new plugin off from the command line when wp-admin is unreachable. The last two flush the object cache and rebuild URL rules, which you need after a release that touches rewrites, as we did after the Slim SEO option incident. A page cache plugin needs its own purge. Prefer redeploying the previous commit to restoring the database, because a restore also discards everything visitors did since the backup, which on a store means lost orders. WordPress has fatal error protection that may pause a broken plugin and email the administrator a recovery link. That is welcome, but it is not a plan.

Finally, keep agent-written code in its own plugin, never as edits inside someone else’s plugin or theme, because updates overwrite those. Watch the logs for the first hour and keep the backup through a quiet week.

From task to a quiet production site

Before the taskBranch from a clean main and export the database.
While the agent worksLocal site only, with every check output pasted into the reply.
Before mergingYou review the diff in the fixed order.
On stagingSame versions as production, key paths clicked, debug log read.
ReleaseFresh export, a human triggers the deploy, caches flushed.
First hourSmoke test, log watch and a rollback ready to go.
First weekWatch error logs and query counts, then retire the backup.
Each stage has one job, and the human holds the deploy button.

Checklist

  • Sort the task into delegate, supervise or keep before you write the prompt.
  • Work on a local or staging copy first, never directly on production.
  • Connect through a dedicated user with the smallest role that covers the job, and revoke the application password afterwards.
  • Turn on WP_DEBUG and WP_DEBUG_LOG with display off, and let the agent read the log.
  • Run php -l, phpcs with the WordPress standard and your tests for every task, with the output pasted.
  • Write a short rules file with versions, prefixes, security rules, boundaries and the verification commands.
  • Enforce the critical rules with permissions, ignore files and CI, not with prose alone.
  • Ask for a plan and a file list before any edit, and use one branch and one commit per task.
  • Review every entry point: nopriv hooks, AJAX, admin-post handlers and REST routes with a real permission_callback.
  • Confirm each state-changing handler has both a capability check and a nonce.
  • Check that input is unslashed, sanitized and validated, and that queries use prepare() or WP_Query.
  • Check that output is escaped once, with the function that matches its destination.
  • Search the diff for suppression comments, edited tests and deleted checks.
  • Measure queries and remote calls with Query Monitor, and test through a cache bypass.
  • Read back what any bulk write stored, such as prices and special characters.
  • Take a database export before release and rehearse the rollback.

About this guide. Parts of this guide come from building and running wpresident.com; those parts are marked as such, and everything else is documentation-level guidance. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.

Frequently asked questions

Which agent is best for WordPress: Claude Code, Cursor or a Codex-style tool?

We have no comparison to offer, so we will not rank them. The difference is mostly workflow: a terminal agent, an editor with an agent built in, or an agent that returns a patch from a copy of your repository. The project setup matters more than the product: a local site, a rules file, checks the agent can run, small tasks and a review order.

Can an AI agent build a whole WordPress site?

It can do a large share of the work. This site was built in November 2026 by Claude Code driving it through NibWP: about 45 pages, a post template, shared header and footer components and several small plugins. It still needed a human to set the standards, review risky changes, notice silent defects and decide what to stop doing. Expect to review more than you write.

Do I need to know PHP to use a coding agent?

You need to read a diff and run commands, and you need to know what you cannot judge. If you cannot read PHP, keep the agent on content, CSS and template work, add static checks such as phpcs, and pay a developer to review anything that touches logins, payments, file uploads or personal data. The agent can explain code line by line, but an explanation is not an audit.

Should the agent have access to my production site?

Not by default. Do the work on a local or staging copy, deploy by a route that a human triggers, and keep production credentials out of the agent. If you do connect a live site through site tools, use a dedicated least-privilege user, a revocable application password, a fresh backup and a narrow list of abilities. Revoke the password when the task ends.

What is a rules file, and what is it called in each tool?

It is a plain text briefing the agent reads at the start of each session: versions, prefixes, security rules, boundaries and the commands that verify work. Claude Code reads CLAUDE.md, Cursor keeps project rules with the code, and Codex-style tools commonly read AGENTS.md. Names and locations change, so confirm them in each tool's documentation. Remember that a rules file is advice and not enforcement.

How do I stop an agent inventing WordPress functions?

You cannot stop it entirely, so make invention cheap to catch. Run php -l and static analysis with a WordPress extension, which flag undefined functions. Turn on WP_DEBUG_LOG so deprecation notices appear. Check unfamiliar names with wp eval and function_exists, or search wp-includes. In the rules file, point to one existing file that shows the pattern you want copied, and let the agent run those checks itself.

Is passing PHPCS enough to call generated code secure?

No. The WordPress Coding Standards catch many omissions, such as unescaped output, unverified nonces and concatenated SQL, but a tool matches patterns and cannot see intent. It cannot tell whether a capability is the right one, whether a route should be public or whether the design leaks data. Use it as a floor, review in a fixed order, and watch for suppression comments the agent adds to silence it.

Why does my change not appear on the site?

Usually a cache is answering. A page cache, object cache or CDN may serve the old copy while the agent insists the work is done. Request the page through a cache bypass, such as an unknown query string, and check your cache plugin's response header. Also ask which cache holds the old copy and what clears it when content changes.

How big should one task be?

Small enough that you will read the whole diff carefully: one behaviour, one acceptance test and a handful of files. A forty-line change gets reviewed, while a nine-hundred-line change gets skimmed. If the agent fails the same check three times, stop and narrow the task. Ask for a plan first, work on a branch and commit after review, so every task is a unit you can revert.

Is it safe to let an agent run PHP on my site?

It is the riskiest ability in the stack. Arbitrary PHP can do anything the site can do. On our build, the site owner told us to stop using NibWP's execute-php ability, and we finished with narrower abilities and a sandbox that switches its plugins off after a fatal error. If you allow it, do so on staging only, with a least-privilege user, a backup and a review of the code before it runs.

W
Written byWPresident EditorialThe WPresident editorial team. Every article says whether it comes from hands-on use or from documentation, and anything paid for is labelled.

Keep reading

Get the Monthly Launch Report

One email a month: the best of last month's articles, new reviews and what changed in WordPress, without the noise.

No spam. Unsubscribe in one click.

Signed and sealed,
The WPresident
↑↓ move↵ openEsc closeAll results