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

How to Build a WordPress Plugin With AI

A complete tutorial: write the spec, have an AI assistant scaffold a small plugin, then review, secure, translate, test and package it like a careful developer.

Written by
WPresident Editorial
Topic
AI

An AI assistant can write a working WordPress plugin in a few minutes. That is the easy part, and it is also the trap. A plugin that activates without errors and shows the right thing on your screen is not yet a plugin you should run on a client site. WordPress executes your code with the full authority of the site, on every request, next to dozens of other plugins you did not write. One missing capability check, one unescaped value or one badly named function can turn a ten-minute experiment into a security hole or a white screen.

The one idea to carry through this guide: the assistant types, you own. You decide what the plugin does and, just as important, what it does not do. You keep it small enough to read every line. You verify it on a disposable site before it goes near a live one. Used that way, an assistant is a fast junior developer who knows the WordPress APIs reasonably well and forgets details often. Used as a vending machine for finished code, it produces plugins that nobody understands, including the person who shipped them.

This tutorial builds one small, complete plugin from an empty folder. It is called Quiet Notice. An administrator enters a one-sentence message and picks a tone on a settings page. A shortcode prints that message anywhere in your content. A tiny stylesheet loads only on pages that use the shortcode. A reset button restores the defaults. Every visible string is translatable, and deleting the plugin removes its data. It is a couple of hundred lines of PHP, yet it touches every topic that matters in larger plugins: hooks, the Settings API, sanitising, escaping, nonces, capability checks, translation, uninstall behaviour, testing and packaging.

Each step follows the same rhythm. First, what to ask the assistant for. Then the code you should expect back. Then what to check in it, because the checking is where this guide spends most of its time. You can type the listings, paste them, or have your assistant produce its own from the spec in Step 2 and compare. Where the two differ, ask whether you understand why. The route has fourteen steps, from deciding whether you need a plugin at all to packaging the zip.

A word on what this guide is. It is a general tutorial built on stable core WordPress functions, independent of any particular assistant, editor or vendor interface. The guide makes no benchmark claims. Check the WordPress developer reference for anything your version treats differently, and run the checks in the later steps against your own code rather than trusting any listing, including these. You need basic PHP, a local WordPress site and a terminal. No Composer, build step or framework is involved.

Key points

  • Write the spec first, with non-goals, minimum versions and a file list, because an assistant fills every gap with its own guess.
  • Keep the plugin small enough to read every line, and commit after each step so a bad suggestion is one command to undo.
  • Sanitise input at the boundary, escape output at the last moment, and match the escaping function to where the value lands.
  • A nonce shows a request was intended and a capability check shows the user is allowed; every handler needs both.
  • Use the Settings API for settings pages, return from shortcodes instead of echoing, and load assets only on pages that need them.
  • Decide uninstall behaviour on purpose: deactivation keeps data, and deleting the plugin removes only what the plugin created.
  • Do not let the assistant mark its own work: test locally with debugging on, run Plugin Check, then install the zip on a clean site.

Step 1: Decide whether a plugin is the right tool

Writing code has never been cheaper, which is exactly why this step matters. Owning code is not cheap. Every plugin you write is a plugin you maintain: you answer for it when PHP gets a new major version, when WordPress changes an API, when someone finds a vulnerability and when a client asks why a page broke. Before you open an assistant, decide where the code should live.

A regular plugin is the right home when the feature should survive a theme change, when you want to switch it on and off from the admin, or when you want to reuse it on several sites. Code pasted into a theme’s functions.php dies with the theme: change themes and the feature silently vanishes. A must-use plugin, a file placed in the mu-plugins folder, always loads, loads before regular plugins and cannot be deactivated from the Plugins screen. That suits site-specific rules that must never be switched off by accident. If the job is layout rather than behaviour, a block pattern or a theme style may need no PHP at all.

The first branch in the figure deserves the most honest answer. If a maintained plugin already solves the problem, installing it usually costs less than writing and owning your own, even when an assistant makes the first draft free. The rule bends as problems get smaller. A one-purpose feature with a stable definition is a fair candidate for your own code. Forms, SEO, caching, backups, security and e-commerce are not. The failure mode to avoid is the AI-assisted reinvention of a large, solved, security-sensitive category.

Be equally honest about this guide’s example: Quiet Notice could be a reusable block or a pattern in a real project. It earns its place here because it is small enough to read in one sitting and still exercises the whole plugin lifecycle. Look for the same in your first project: a one-sentence purpose, a small data model and no external services.

Before you continue, write one sentence that says who can do what and which data gets stored. If you cannot answer all three, you are not ready to prompt, and the assistant will happily fill the gaps for you.

Where should this code live?

What is the code for?
A maintained plugin already solves itInstall and configure that plugin. You own less code, and someone else patches it.
It must always run and never be switched off by accidentPut it in a must-use plugin. Expect no activation hooks and no update notices.
It is a feature that should outlive the theme and be switchableWrite a regular plugin. This is the case the rest of this guide covers.
It only changes layout or styling for one themeUse the theme, a child theme, a block pattern or theme styles instead of PHP.
Four questions decide whether you write a plugin, a must-use plugin, theme code or nothing at all.

Step 2: Write the spec before you open the assistant

The specification is the most valuable thing you write in this whole process. An assistant has no idea what you meant, only what you said, and every gap becomes a guess: a feature you did not ask for, a library you did not want, a data structure you will regret. A good spec is short, concrete and testable. It names the purpose, the roles, the inputs and outputs, the stored data, the constraints, the files and, crucially, the non-goals. Here is the spec for the plugin in this guide.

Plugin name: Quiet Notice
Slug and text domain: quiet-notice
Function and option prefix: qnotice_
Purpose: let an administrator store one short notice and print it anywhere with a shortcode.
Minimum versions: WordPress 6.0, PHP 7.4.
Admin: one page under Settings. Fields: show_notice (checkbox), notice_text (one line of plain text), notice_tone (info, warning or success). Only users with manage_options can view or save.
Front end: the shortcode [quiet_notice] prints the message in a div. An optional tone attribute overrides the saved tone. It prints nothing when disabled or empty.
Storage: one option named qnotice_settings, stored as an array.
Security: sanitise on save, escape on output, capability check on every admin action, nonce on every form.
Extras: a Reset to defaults button. All visible strings translatable with the quiet-notice text domain.
Style: plain procedural PHP, WordPress coding standards, no classes, no Composer, no build step, no external HTTP calls.
Files: quiet-notice.php, includes/settings.php, includes/shortcode.php, assets/qnotice.css, uninstall.php.
Uninstall: delete the option and nothing else.
Non-goals: no block, no widget, no REST endpoint, no custom table, no analytics.
Done when: the test plan passes on a clean install with WP_DEBUG on.

Four lines do most of the protective work. The minimum versions stop the assistant from using features your hosting does not have, which it will otherwise do, because its knowledge is a snapshot and not your environment. The file list prevents a sprawling structure of autoloaders and service classes around a hundred lines of logic. The non-goals stop feature creep, and assistants are generous with features. The last line, “done when”, turns the spec into a test plan that you write down before any code exists.

Then do not ask for code yet. Ask the assistant to restate the spec in its own words, list the files it intends to create, name the hooks and core functions it plans to use, and flag anything ambiguous. That exposes misunderstandings while they are still cheap. If it proposes a custom table, a build step or a class hierarchy, tighten the spec instead of arguing about the code.

Keep the stable parts of your instructions in a standing file that your tool reads at the start of every session: the versions you target, the prefix, the coding standard, the security rules, a ban on external libraries unless asked, and one line that matters more than the rest: “Never invent WordPress functions or hooks; if you are unsure that something exists, say so.”

Finally, work in slices: one prompt per file or behaviour, and ask for a change rather than a rewritten file. A full rewrite after a one-line request quietly turns a reviewed plugin back into an unreviewed one.

Step 3: Prepare a safe workshop

Never develop on a live site, and never point an assistant that can run commands at one. Create a local WordPress site on your own machine, using a local development app, a container setup or WordPress’s own tooling for disposable environments. What matters is that it is disposable and that nothing on it is precious. Run it on the oldest PHP version in your spec, so that newer syntax from the assistant fails at once instead of on a customer’s host.

Make the plugin folder the only place the assistant works. Create it inside the plugins directory and put it under version control straight away, so that every step in this tutorial ends with a commit and a bad suggestion costs you one command to undo.

$ cd wp-content/plugins
$ mkdir quiet-notice
$ cd quiet-notice
$ git init

Turn on debugging before the first line of plugin code exists, so that every notice and deprecation shows up while the code is fresh. In wp-config.php, above the line that tells you to stop editing, add the following. Errors go to wp-content/debug.log instead of into your pages.

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_ENVIRONMENT_TYPE', 'local' );

Install two helper plugins on the local site only: Query Monitor, which shows the hooks, queries, scripts, styles and PHP errors of each request (Step 13), and Plugin Check, the official review tool from the WordPress.org Plugins team (Step 14).

If your assistant is an agent that can run shell commands, treat its permission prompts as code review. Read the command before you approve it, particularly anything containing rm, a database command or a site-level command. Do not paste database passwords, salts, API keys or real customer data into prompts, and do not give it credentials for production or staging servers.

localwp.com
The Local product page: a desktop application for creating and running WordPress sites on your own computer
A local site gives the assistant a safe place to be wrong: you can break it, reset it or delete it without touching a live site.

Step 4: Scaffold the plugin with a header, a guard and a prefix

Start with how WordPress finds and runs a plugin. It scans the plugins directory, reads the comment block at the top of the PHP files directly inside each plugin folder, and treats a file with a Plugin Name line as the main file. On every request it loads the main files of active plugins early, before the theme, and then fires hooks as the request progresses. Nothing in your code runs unless the main file includes it, and nothing happens at the right moment unless you attach a function to a hook.

Two consequences shape the structure. Code at the top level of a file runs on every request, front end and admin, so the top level should only define constants, include files and register hooks. And all plugins share one global namespace for functions, constants and options, so every name you create needs a unique prefix. The spec chose qnotice_, and every function, constant, option and handle in the plugin starts with it. A function called get_settings or render_notice is a future collision with someone else’s plugin. This is the folder you are building.

quiet-notice/
  quiet-notice.php
  uninstall.php
  includes/
    settings.php
    shortcode.php
  assets/
    qnotice.css

Ask the assistant for the main file only, then read it before moving on.

<?php
/**
 * Plugin Name:       Quiet Notice
 * Description:       Prints one short notice anywhere with a shortcode. Managed from a settings page.
 * Version:           0.1.0
 * Requires at least: 6.0
 * Requires PHP:      7.4
 * Author:            Example Author
 * License:           GPL-2.0-or-later
 * Text Domain:       quiet-notice
 */

defined( 'ABSPATH' ) || exit;

define( 'QNOTICE_VERSION', '0.1.0' );
define( 'QNOTICE_FILE', __FILE__ );

require_once __DIR__ . '/includes/settings.php';
require_once __DIR__ . '/includes/shortcode.php';

Check it line by line. WordPress reads the header without running the file, and the two Requires lines can stop activation on unsupported sites. Text Domain must equal the plugin slug and the string you pass to every translation function in Step 10. The ABSPATH guard makes the file do nothing when someone requests it directly, outside WordPress. The constants give you a version for cache-busting assets and a file path that plugins_url needs later. There is no closing PHP tag, because stray whitespace after one can corrupt headers and feeds.

The two included files do not exist yet. Create each with only the opening PHP tag and the guard line, activate the plugin on your local site, confirm there is no error in the debug log, and commit.

What a small plugin is made of

Header commentIdentity and requirements that WordPress reads without running the file.
Guard and constantsExit if WordPress is absent, define the version and file path, and do nothing else.
IncludesOne file per job, so a diff stays small.
HooksThe only entry points. Each add_action or add_filter line states when a function may run.
HandlersPlain prefixed functions that do the work and run only when their hook fires.
uninstall.phpA separate file WordPress runs when the plugin is deleted, with none of your other code loaded.
Six layers, top to bottom: each has one job, and only the hooks decide when your code runs.

Step 5: Add behaviour with hooks: the shortcode

Now give the plugin its first visible behaviour. Ask for includes/shortcode.php and the stylesheet only, and state three requirements in the prompt: the callback must return a string, the stylesheet must load only when the shortcode prints, and the tone attribute must be checked against the list of known tones.

<?php
defined( 'ABSPATH' ) || exit;

function qnotice_register_assets() {
	wp_register_style(
		'qnotice',
		plugins_url( 'assets/qnotice.css', QNOTICE_FILE ),
		array(),
		QNOTICE_VERSION
	);
}
add_action( 'wp_enqueue_scripts', 'qnotice_register_assets' );

function qnotice_shortcode( $atts ) {
	$settings = qnotice_get_settings();

	if ( empty( $settings['show_notice'] ) || '' === $settings['notice_text'] ) {
		return '';
	}

	$atts = shortcode_atts(
		array( 'tone' => $settings['notice_tone'] ),
		$atts,
		'quiet_notice'
	);

	$tone = sanitize_key( $atts['tone'] );
	if ( ! array_key_exists( $tone, qnotice_tones() ) ) {
		$tone = 'info';
	}

	wp_enqueue_style( 'qnotice' );

	return sprintf(
		'<div class="qnotice qnotice--%1$s" role="note">%2$s</div>',
		esc_attr( $tone ),
		esc_html( $settings['notice_text'] )
	);
}
add_shortcode( 'quiet_notice', 'qnotice_shortcode' );
.qnotice {
	margin: 1em 0;
	padding: 0.75em 1em;
	border-inline-start: 4px solid #2271b1;
	background: #f0f6fc;
	color: #1d2327;
}

.qnotice--warning { border-inline-start-color: #dba617; background: #fcf9e8; }
.qnotice--success { border-inline-start-color: #00a32a; background: #edfaef; }

Read the shortcode function as a sequence of decisions. It leaves early when the notice is disabled or empty, so nothing is enqueued needlessly. The shortcode_atts call supplies defaults and, with its third argument, lets other code filter the attributes. The tone goes through sanitize_key and is then compared with your own list, so a value typed by an author never becomes a CSS class unchecked. The style is registered on wp_enqueue_scripts but enqueued only inside the callback, the usual way to load assets on demand. The version argument changes the query string when you bump the constant, so browsers fetch the new file.

The most common slip in shortcodes is echoing instead of returning. WordPress runs the callback while it is still building the content string, so anything you echo lands before the content, often above the whole post, and the shortcode’s own place in the text stays empty.

The callback calls two helpers that live in settings.php. Until Step 6 is written the shortcode would cause a fatal error, so finish Step 6 before you put it in a page. Commit now.

From shortcode to HTML on the page

  1. Author saves the tagThe post content contains the text [quiet_notice]. Nothing runs yet.
  2. Visitor requests the pageYour plugin loads and wp_enqueue_scripts fires. The stylesheet is registered, not printed.
  3. Content is renderedThe the_content filter hands the post text to core, which scans it for registered shortcodes.
  4. Your callback runsIt reads the settings, checks the tone, enqueues the style and returns a string.
  5. WordPress swaps the tagThe returned string replaces the tag. Anything echoed instead lands in the wrong place.
  6. Page is finishedA style enqueued this late is printed near the end of the page.
The shortcode is plain text until the content is rendered; your callback must hand back a string for WordPress to swap in.

Step 6: Store the settings with the Settings API

Settings are where plugins often go wrong, because the job looks mechanical: a form, a button, an option. Tell the assistant to use the Settings API, by name. It is a small set of core functions that lets WordPress do the dangerous plumbing. It prints a nonce with the form, posts to options.php, checks the nonce and the capability for your settings group, passes the value through your sanitise callback and stores the result. A hand-rolled form must rebuild all of that, and every piece is a place to forget something.

Storage comes first. Keep related settings in one option holding an array, one row instead of three, and read it through one getter that merges the saved values over defaults. That is why a missing key never raises a notice and a new setting needs no migration. The sanitise callback is the single gate every saved value passes through. An unchecked box is absent from the post, so it becomes 0. Text is cleaned. The tone is accepted only if it is a key in your own list, which is an allowlist and the strongest form of validation there is. Put this at the top of includes/settings.php.

<?php
defined( 'ABSPATH' ) || exit;

function qnotice_defaults() {
	return array(
		'show_notice' => 1,
		'notice_text' => '',
		'notice_tone' => 'info',
	);
}

function qnotice_tones() {
	return array(
		'info'    => __( 'Information', 'quiet-notice' ),
		'warning' => __( 'Warning', 'quiet-notice' ),
		'success' => __( 'Good news', 'quiet-notice' ),
	);
}

function qnotice_get_settings() {
	$saved = get_option( 'qnotice_settings', array() );
	return wp_parse_args( is_array( $saved ) ? $saved : array(), qnotice_defaults() );
}

function qnotice_sanitize_settings( $input ) {
	$input = is_array( $input ) ? $input : array();
	$tone  = isset( $input['notice_tone'] ) ? sanitize_key( $input['notice_tone'] ) : 'info';

	return array(
		'show_notice' => empty( $input['show_notice'] ) ? 0 : 1,
		'notice_text' => isset( $input['notice_text'] ) ? sanitize_text_field( $input['notice_text'] ) : '',
		'notice_tone' => array_key_exists( $tone, qnotice_tones() ) ? $tone : 'info',
	);
}

function qnotice_register_settings() {
	register_setting(
		'qnotice_group',
		'qnotice_settings',
		array( 'sanitize_callback' => 'qnotice_sanitize_settings' )
	);

	add_settings_section( 'qnotice_main', '', '__return_false', 'quiet-notice' );

	add_settings_field( 'qnotice_enabled', __( 'Show notice', 'quiet-notice' ), 'qnotice_field_enabled', 'quiet-notice', 'qnotice_main' );
	add_settings_field( 'qnotice_message', __( 'Message', 'quiet-notice' ), 'qnotice_field_message', 'quiet-notice', 'qnotice_main', array( 'label_for' => 'qnotice_message' ) );
	add_settings_field( 'qnotice_tone', __( 'Tone', 'quiet-notice' ), 'qnotice_field_tone', 'quiet-notice', 'qnotice_main', array( 'label_for' => 'qnotice_tone' ) );
}
add_action( 'admin_init', 'qnotice_register_settings' );

One detail trips up assistants regularly. Before your callback runs, options.php has already removed the slashes WordPress adds to posted data, so calling wp_unslash again inside the callback would damage legitimate backslashes in the text. Superglobals that you read yourself are different, as Step 8 shows.

What happens when an administrator clicks Save

  1. Form is postedThe browser sends qnotice_settings[notice_text] and friends, plus the hidden nonce fields, to options.php.
  2. Nonce and capability checkedWordPress verifies the group nonce and the capability, manage_options by default.
  3. Slashes removedPosted values are unslashed before your code sees them, so do not unslash again.
  4. Your sanitise callback runsThis is the gate: allowlist the tone, clean the text, turn the checkbox into 0 or 1.
  5. One option row is writtenupdate_option stores the cleaned array under qnotice_settings.
  6. Browser is redirected backThe settings page loads again and reads the stored values through your getter.
The Settings API does the nonce, capability and storage work; your only code in the path is the sanitise callback.

Step 7: Build the settings page

Now the form controls and the page. Every value that goes back into the markup is escaped for its context. The group passed to settings_fields must match the first argument of register_setting, and the slug passed to do_settings_sections must match the one used in add_settings_field. When they drift apart, saving fails with an error page, and the cause is a typo. Append this to the same file. The lower form is explained in Step 9.

function qnotice_field_enabled() {
	$settings = qnotice_get_settings();
	?>
	<label>
		<input type="checkbox" name="qnotice_settings[show_notice]" value="1" <?php checked( $settings['show_notice'], 1 ); ?>>
		<?php esc_html_e( 'Print the notice wherever the shortcode is used', 'quiet-notice' ); ?>
	</label>
	<?php
}

function qnotice_field_message() {
	$settings = qnotice_get_settings();
	?>
	<input type="text" id="qnotice_message" class="large-text" name="qnotice_settings[notice_text]" value="<?php echo esc_attr( $settings['notice_text'] ); ?>">
	<p class="description"><?php esc_html_e( 'Plain text, one sentence.', 'quiet-notice' ); ?></p>
	<?php
}

function qnotice_field_tone() {
	$settings = qnotice_get_settings();
	?>
	<select id="qnotice_tone" name="qnotice_settings[notice_tone]">
		<?php foreach ( qnotice_tones() as $value => $label ) : ?>
			<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $settings['notice_tone'], $value ); ?>>
				<?php echo esc_html( $label ); ?>
			</option>
		<?php endforeach; ?>
	</select>
	<?php
}

function qnotice_add_menu() {
	add_options_page(
		__( 'Quiet Notice', 'quiet-notice' ),
		__( 'Quiet Notice', 'quiet-notice' ),
		'manage_options',
		'quiet-notice',
		'qnotice_render_page'
	);
}
add_action( 'admin_menu', 'qnotice_add_menu' );

function qnotice_render_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only flag that changes nothing.
	$was_reset = isset( $_GET['qnotice_reset'] );
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

		<?php if ( $was_reset ) : ?>
			<div class="notice notice-success is-dismissible">
				<p><?php esc_html_e( 'Settings reset to defaults.', 'quiet-notice' ); ?></p>
			</div>
		<?php endif; ?>

		<form action="options.php" method="post">
			<?php
			settings_fields( 'qnotice_group' );
			do_settings_sections( 'quiet-notice' );
			submit_button();
			?>
		</form>

		<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
			<input type="hidden" name="action" value="qnotice_reset">
			<?php wp_nonce_field( 'qnotice_reset', 'qnotice_nonce' ); ?>
			<?php submit_button( __( 'Reset to defaults', 'quiet-notice' ), 'secondary', 'submit', false ); ?>
		</form>
	</div>
	<?php
}

Now test the page. Open Settings, then Quiet Notice, type a message, pick a tone, save and reload. The values should persist, an unchecked box should stay unchecked, and the debug log should stay empty. Put the shortcode in a page and view it: the notice appears with its style, and it disappears when you untick the box. Then confirm what was actually stored, and commit.

$ wp option get qnotice_settings --format=json

Step 8: Sanitise on the way in, escape on the way out

Two words get confused constantly, and the confusion sits behind most plugin vulnerabilities. Sanitising happens on the way in: you take whatever arrived and make it conform to what you expect, or reject it. Escaping happens on the way out: you take a value you are about to print and make it safe for the exact place it lands. They solve different problems. Sanitising on save does not make output safe, because data can reach your output without passing through your form: through an import, another plugin, a direct database edit or a REST request. And escaping on output cannot repair a value that should never have been stored.

Apply three rules. Validate against an allowlist where you can: the tone list is the model, and it is safer than trying to strip bad values. Sanitise with the function that matches the data: sanitize_text_field for a single line, sanitize_textarea_field when line breaks matter, sanitize_key for identifiers, absint for counts and IDs, sanitize_email for addresses and esc_url_raw for URLs you store. And escape late, as close to the output as possible, with the function that matches the context rather than the first one that comes to mind. The figure maps the four contexts you will meet most often.

When your own code reads a superglobal, as an admin-post handler does, the pattern is three words: check it exists, unslash it, sanitise it. WordPress adds slashes to the request arrays for historical reasons, and wp_unslash removes them.

$text = isset( $_POST['notice_text'] ) ? sanitize_text_field( wp_unslash( $_POST['notice_text'] ) ) : '';

The slips are predictable. Escaping on the way into the database, which corrupts stored text and gives a false sense of safety. Sanitising on the way out, which silently alters what the user wrote. Using esc_html inside an attribute, or esc_attr for a URL. Printing a translated string without an escaping variant: use esc_html__ and esc_html_e so the translator’s text is escaped too. And escaping a finished concatenated string instead of each value as it is inserted, which is what the sprintf in the shortcode does.

When you really must print markup that an author wrote, wp_kses_post applies the allowlist WordPress uses for post content, and wp_kses accepts one you define. Quiet Notice stores plain text and prints it with esc_html, which is the simplest correct answer and the reason the settings field says plain text.

Which escaping function fits?

Where will the value be printed?
Between HTML tags, as textesc_html, or esc_html__ and esc_html_e for translated strings.
Inside an HTML attribute such as value or classesc_attr, or esc_attr__ for translated strings.
As a link or image addressesc_url when printing. esc_url_raw when storing the URL or using it in a redirect.
As markup the author is allowed to writewp_kses_post, or wp_kses with an allowlist you define.
Pick the function from where the value lands, not from what the value is.

Step 9: Add nonces and capability checks to every handler

Every action that changes something needs two separate answers: is this user allowed, and did they mean to do it? The capability check answers the first and the nonce answers the second. They are constantly confused, and an assistant that adds one and calls the handler secured has left half the door open.

A capability check asks what the current user may do, through current_user_can and a capability such as manage_options. Check capabilities rather than roles, and never use is_admin as a permission test. That function only says the request is for an admin screen, and it returns true for any visitor who calls admin-ajax.php or admin-post.php. A nonce is a short-lived token tied to the user, the session and a named action. It shows that the request came from a page your plugin rendered for that user a short time ago, which defeats forged requests from other sites. It is not a secret, it expires after a limited window of roughly a day by default, and it proves nothing about permission: a subscriber holds valid nonces too.

The reset button from Step 7 shows both. Its form posts to admin-post.php with a hidden action field, which routes to a hook named after the action. Handlers for logged-in users go on admin_post_ plus the action name. The nopriv variant is for logged-out visitors, and an admin task must never use it.

function qnotice_handle_reset() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die(
			esc_html__( 'You do not have permission to do that.', 'quiet-notice' ),
			'',
			array( 'response' => 403 )
		);
	}

	check_admin_referer( 'qnotice_reset', 'qnotice_nonce' );

	update_option( 'qnotice_settings', qnotice_defaults() );

	wp_safe_redirect( add_query_arg( 'qnotice_reset', '1', admin_url( 'options-general.php?page=quiet-notice' ) ) );
	exit;
}
add_action( 'admin_post_qnotice_reset', 'qnotice_handle_reset' );

Add this to includes/settings.php. The capability check comes first because it is cheap. Then check_admin_referer verifies the nonce, using the action and field name from the form, and stops the request if it fails. Only then does the handler change anything. It ends with wp_safe_redirect, which refuses other hosts, then exit, because a redirect header does not stop PHP from running on.

The phpcs:ignore comment in the page function names the rule and the reason, which is the honest way to quiet a scanner on a display-only read. A read that acts on the value needs a nonce first.

The same pair applies wherever your code is reachable. AJAX handlers need check_ajax_referer plus a capability check, and wp_ajax_nopriv_ only for logged-out actions. REST routes need a permission_callback, and current WordPress versions warn when it is missing. At every handler, ask your assistant to name the capability and the nonce action in plain words before you accept the code. If it cannot, the handler is not finished.

Step 10: Make every string translatable

Translation is cheap to do now and painful to retrofit. The rule is simple: every string a person reads goes through a translation function with your text domain, and then through the right escaping function. The domain, quiet-notice, is the one from the plugin header, and it must be a literal in every call, not a variable or a constant, because extraction tools read your source without running it.

__ returns a translated string, and esc_html__ and esc_attr__ return it escaped. esc_html_e prints it escaped; the plain _e prints unescaped and is best avoided. _x adds context for ambiguous words, such as a noun and a verb that share spelling. _n handles plurals, where the number picks the form. Placeholders belong inside the string and are filled with sprintf, never by concatenating fragments, because word order differs between languages. A translators comment placed directly before the call explains each placeholder.

$text = sprintf(
	/* translators: %d: number of characters left. */
	_n( '%d character left', '%d characters left', $left, 'quiet-notice' ),
	$left
);

echo esc_html( $text );

Three slips recur. The first is translating at file load time, for instance in a top-level array or constant. Translations are not ready yet, and recent WordPress versions raise a notice when text is requested too early. That is why qnotice_tones is a function that builds its labels when called. The second is a variable inside the call, as in __ with a variable first argument, which no tool can extract. The third is concatenation, where a sentence is assembled from pieces that a translator never sees together.

Generate the catalog with WP-CLI from the plugin folder. The command scans your source for translation calls and writes a template that translators work from.

$ mkdir -p languages
$ wp i18n make-pot . languages/quiet-notice.pot

Open the generated file and check that every visible string appears; a missing one was never wrapped. On loading: for a plugin distributed through the WordPress.org directory, community translations load automatically for the text domain that matches the plugin slug, so no loading call is needed in current versions. If you ship your own translation files in a languages folder, add the Domain Path header and load them with load_plugin_textdomain on init or later, and confirm the details in the current developer handbook for your minimum version.

Step 11: Decide what happens on deactivation and uninstall

Installing, deactivating and deleting a plugin are three different events, and assistants tend to blur them. Activation runs once, when an administrator clicks Activate, so it is the place to create something the plugin needs, such as a custom table. It does not run on updates. Deactivation is reversible, so it must leave user data alone and only stop what the plugin started, such as scheduled events. Uninstall is final: it runs when the plugin is deleted from the Plugins screen, and it is the only place to remove data.

Quiet Notice needs no activation or deactivation code, because the getter supplies defaults and nothing is scheduled. Its uninstall behaviour is one line of intent: delete the option and nothing else. Use an uninstall.php file in the plugin root. Three details matter. The file must check the WP_UNINSTALL_PLUGIN constant so it cannot be run directly. WordPress loads only that file, not your main plugin file, so your own functions do not exist and you may call only core functions. And on multisite, options are stored per site, so a network-wide delete has to visit every site.

<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

if ( is_multisite() ) {
	foreach ( get_sites( array( 'fields' => 'ids' ) ) as $site_id ) {
		switch_to_blog( $site_id );
		delete_option( 'qnotice_settings' );
		restore_current_blog();
	}
} else {
	delete_option( 'qnotice_settings' );
}

The function get_sites returns a limited number of sites per call by default, so a very large network needs paging through its number and offset arguments. The decision a human must make is how much to delete. A small settings plugin should delete its own options. A plugin that holds user content, such as orders, form entries or custom posts, should never destroy it silently: offer a setting, off by default, that says all data is deleted on uninstall. Never delete posts, users or tables you did not create. An assistant told to clean up on uninstall will sometimes do exactly that.

Test it by deleting the plugin on the local site, then asking WP-CLI for the option. It should report that the option does not exist.

$ wp option get qnotice_settings

Three lifecycle events, three different jobs

ActivationDeactivationUninstall
When it runsOnce, when an administrator clicks ActivateWhen an administrator clicks DeactivateWhen the plugin is deleted from the Plugins screen
Typical jobCreate what the plugin needs, such as a tableStop what you started, such as scheduled eventsRemove your own options, tables and files
User dataWrite only what is neededKeep all of itDelete yours, or ask first if it is valuable
Your code loaded?YesYesNo, only uninstall.php runs
Common slipAssuming it runs on every updateDeleting data hereCalling your own functions, which do not exist
Keep each event to its own job, and put data removal only in the last column.

Step 12: Review the assistant’s code line by line

Review is a different activity from writing, and the assistant cannot do it for itself. Read the diff after every prompt with the same questions for every line. What runs this, and when? Who can trigger it? What input does it trust? What does it print, and where? What does it store, and what does it leave behind? Read the hook lines first, because they are the map of when your code runs.

A typical first draft shows why. This handler runs, saves and redirects, so it appears to work on the first try.

add_action( 'admin_post_qnotice_save', function () {
	update_option( 'qnotice_message', $_POST['message'] );
	wp_redirect( $_SERVER['HTTP_REFERER'] );
} );

It has no capability check and no nonce. It stores a raw superglobal with its slashes still on and nothing sanitised. It redirects to a header the sender controls, then fails to stop with exit. And as an anonymous function, nobody can unhook it. Working is not the test. These are the patterns to look for on every read.

  • Invented or outdated APIs: functions and hooks that sound right but do not exist, removed functions and wrong argument orders. Look up every unfamiliar name in the developer reference.
  • PHP newer than your header: match expressions, named arguments, the nullsafe operator or constructor promotion in a plugin that claims PHP 7.4.
  • Missing guards: no capability check, no nonce, or is_admin used as a permission test.
  • Output that is unescaped or escaped with the wrong function for its context.
  • Assets loaded on every page, queries inside loops, and remote requests on every page view with no cache.
  • Raw SQL built by concatenation instead of the prepare method, or a custom table where an option would do.
  • Calls you did not ask for: external HTTP requests, tracking, or extra features outside your non-goals.
  • Errors hidden instead of fixed: the at-sign suppressor, isset checks sprinkled everywhere, a try block that swallows exceptions, or escaping removed to cure double-encoded text.

A second opinion helps if you scope it. Open a fresh session, give it only the code and the spec, and ask it to act as a plugin reviewer and list problems without rewriting anything. Treat the result as a list of things to check. It is another model with similar blind spots, so it directs your attention but gives no verdict. The verdict comes from the tools in Step 14 and from running the code.

Where assistant slips sit between cosmetic and dangerous

How to read this: each row is one option, and its dot shows where it sits between Cosmetic and Dangerous. Placement is an editorial judgement, not a measurement.

  1. 1Overbuilt structure for a tiny jobCosts review time and rarely breaks anything.
  2. 2Unprefixed names or wrong text domainCollides with other code or breaks translation.
  3. 3Assets loaded on every pageSlows pages and clutters every site.
  4. 4Invented or outdated functionA fatal error or a silent failure at runtime.
  5. 5Output not escapedOpens the door to script injection.
  6. 6Handler without capability check or nonceLets the wrong user, or a forged request, change the site.
An editorial ranking to decide where to spend review time first; the positions are judgement, not measurements.

Step 13: Test it on a local site and in Query Monitor

Write the test plan from the spec before you run anything, not from the code, because tests derived from code tend to confirm whatever the code already does. For Quiet Notice the plan fits in eight lines.

  1. Activate on a clean site with debugging on: the log stays empty.
  2. Open the settings page as an administrator, save, reload: values persist, and an unchecked box stays unchecked.
  3. Use the shortcode in a page: it prints, it prints nothing when disabled or empty, the tone attribute overrides the saved tone, and an unknown tone falls back to information.
  4. Hostile input: save a message containing markup and quotes, then view the page source. Nothing may execute, and the HTML must not break.
  5. Permissions: as a user without manage_options, the settings page must refuse access. Submit the reset form with a missing or altered nonce and confirm it is rejected.
  6. Reset restores the defaults and shows the notice.
  7. Deactivate keeps the settings. Delete removes them.
  8. Switch to the oldest PHP version you claim to support and repeat steps 1 to 3.

Two command-line checks catch the cheap failures. A syntax check on every file, and a shortcode rendered outside the browser.

$ php -l quiet-notice.php
$ php -l includes/settings.php
$ php -l includes/shortcode.php
$ wp eval 'echo do_shortcode( "[quiet_notice tone=warning]" );'

Query Monitor then shows what the request really did. Its PHP errors panel lists notices and deprecations from your code. Its hooks panel confirms that your callbacks sit on the hooks you intended. The database queries panel should show no query of your own for the settings, because a small autoloaded option comes from a cache filled at startup. The styles panel should list the qnotice stylesheet only on pages that use the shortcode.

Finally, automate what you can. A small unit test for the sanitise function pins the rule that matters most, and the WordPress handbook documents the PHPUnit setup that WP-CLI can scaffold for a plugin.

class Test_Sanitize extends WP_UnitTestCase {
	public function test_unknown_tone_falls_back_to_info() {
		$clean = qnotice_sanitize_settings( array( 'notice_tone' => 'nonsense' ) );
		$this->assertSame( 'info', $clean['notice_tone'] );
	}
}
wordpress.org
The Query Monitor plugin page: a developer tool that shows queries, hooks, scripts, styles and PHP errors for each WordPress request
Query Monitor shows what each request really did, so you can confirm your hooks, your assets and your database use.

Step 14: Run Plugin Check, package and ship

Plugin Check is the official review tool from the WordPress.org Plugins team. It runs static checks over your files, plus optional runtime checks that load the plugin, and reports errors and warnings with a file and line. Install it on the local site, choose your plugin, run it, and fix every error. For each warning, either fix it or write down why it is acceptable.

Add one check outside WordPress. A coding-standards scan with PHP_CodeSniffer and the WordPress Coding Standards catches escaping, nonce and naming problems, and PHP static analysis with WordPress stubs catches calls to functions that do not exist, the most direct test for invented APIs. Install the tools with Composer in a tooling folder next to the plugin folder, not inside it, so the plugin stays dependency-free, and run the scan from there.

$ vendor/bin/phpcs --standard=WordPress ../quiet-notice

Then the housekeeping. Bump the version in the header and the constant together, and in the readme if you have one. For the WordPress.org directory, write readme.txt in its standard format, with a short description, installation notes, an FAQ and a changelog, and make its stable tag match the version. Declare a GPL-compatible licence. Remove what users do not need: version control folders, dependency folders, tests and tooling configuration. Then build the zip with the plugin folder as its single top-level directory.

$ cd wp-content/plugins
$ zip -r quiet-notice.zip quiet-notice -x "quiet-notice/.git/*" -x "quiet-notice/node_modules/*" -x "quiet-notice/tests/*"

Install the zip, not your working folder, on a fresh local site through the upload screen, activate it and run the test plan again. A zip can reveal missing files and wrong paths that your working copy hid.

Last, be clear about responsibility. If you distribute the plugin, you answer for its code, its licence and its updates, whoever or whatever typed the first draft. The copyright status of AI output and your assistant’s terms are legal questions this guide cannot settle, and nothing here is legal advice, so check both before you publish, and read the current directory guidelines before you submit. Plan for maintenance too: test every new WordPress release on a staging copy, keep the spec and test plan in the repository, and change the plugin the same way you built it, one reviewed diff at a time.

wordpress.org
The Plugin Check page in the WordPress.org plugin directory: the official tool for checking a plugin against directory requirements and best practices
Plugin Check gives an independent report on your files, which is what the assistant cannot give you about its own work.

Checklist

  • Decided that a plugin, rather than a theme file, a must-use plugin or an existing plugin, is the right home.
  • Wrote a one-page spec with minimum versions, a file list, a prefix and explicit non-goals.
  • Built on a disposable local site with WP_DEBUG and WP_DEBUG_LOG on, inside a git repository.
  • Asked for one file or one behaviour per prompt and committed after each reviewed step.
  • Confirmed every function, constant, option and handle carries the unique prefix.
  • Confirmed shortcodes return strings instead of echoing, and assets load only when needed.
  • Used the Settings API with a sanitise callback that allowlists every value.
  • Read every superglobal with isset, wp_unslash and a matching sanitise function.
  • Escaped every output at the point of printing, with the function for its context.
  • Gave every handler a capability check and a verified nonce, then redirected safely and exited.
  • Wrapped every visible string in a translation call with a literal text domain, and generated a .pot file.
  • Wrote uninstall.php to remove only the plugin’s own data, and tested a real delete.
  • Looked up every unfamiliar function or hook in the developer reference.
  • Ran the test plan, including hostile input, a low-privilege user and the oldest supported PHP.
  • Ran Plugin Check and a coding-standards scan, and fixed or justified every finding.
  • Installed the packaged zip on a clean site before sharing it.

About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. 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

Can an AI assistant write a safe WordPress plugin?

It can write code that follows safe patterns, and it can just as easily leave them out without any sign that something is missing. Safety comes from the process around it: a tight spec, small diffs, a line-by-line review for capability checks, nonces, sanitising and escaping, and tests on a local site. Treat the assistant as a fast drafter and yourself as the owner who verifies.

Which AI assistant should I use for plugin development?

Choose by workflow rather than by name. A chat window suits snippets and explanations, an editor assistant suits reading and changing files in context, and a terminal agent suits multi-file changes and running commands. Whichever you use, give it your spec and versions, restrict it to the plugin folder, read every diff and keep your own tests. Features and limits change often, so check current documentation before relying on a specific capability.

Should a small plugin use classes or plain functions?

Plain prefixed functions are fine at this size and are easier to read in a review. Classes earn their place when you need shared state, several related components or unit tests that replace dependencies. Assistants often add classes, namespaces and autoloaders by default, so say in the spec which style you want. Whatever you choose, keep a unique prefix or namespace, because collisions are the real risk.

How do I stop the assistant from using outdated or invented functions?

You cannot stop it completely, so build a check. State your minimum versions in the spec, tell it to say when it is unsure, and look up every unfamiliar function in the developer reference. Run PHP static analysis with WordPress stubs, which flags calls to functions that do not exist, and run Plugin Check. A deprecation notice in the debug log is another early signal.

What is the difference between sanitising and escaping?

Sanitising cleans or validates data as it arrives, before you store or use it. Escaping makes a value safe for its destination as you print it, whether that is HTML text, an attribute or a URL. You need both, because stored data can come from places other than your form, and neither substitutes for the other. Sanitise at the boundary, and escape late with the function that fits the output context.

Do I still need a nonce if I already check capabilities?

Yes. A capability check says the user may perform the action. A nonce says this request was intended by that user, from a page your plugin showed them. Without a nonce, another site can trick a logged-in administrator's browser into submitting a request that passes the capability check. Without the capability check, any user's valid nonce would be enough. Use both on every handler that changes state.

Why does my shortcode output appear at the top of the page?

Almost always because the callback echoes its HTML instead of returning it. WordPress calls the shortcode while building the content string, so echoed output prints immediately, before the content, and the shortcode's own position stays empty. Build a string and return it, escaping each value as you insert it. If you use a template file, capture its output with output buffering and return the buffer.

Do I need load_plugin_textdomain?

Not for a plugin hosted in the WordPress.org directory in current WordPress versions, where translations for the plugin slug load automatically. If you bundle your own translation files, add the Domain Path header and load them on init or later. Never call translation functions at file load time, and confirm the details in the current developer handbook for the minimum version you support.

What does Plugin Check catch, and is it enough?

It checks plugin files against directory requirements and common problems in areas such as security, internationalisation, performance and the readme. It is not enough on its own. It cannot know whether your plugin does what the spec says, so you still need your test plan, a coding-standards scan and a human read. Treat a clean report as the floor, not the finish line.

Who owns AI-generated plugin code, and can I sell or share it?

That is a legal question, and this is not legal advice. The position on copyright in AI output differs between jurisdictions and can change, and your assistant's terms of service apply as well. If you plan to distribute under the GPL or sell the plugin, check both, keep notes on what you wrote and what was generated, and ask a qualified lawyer if the plugin matters commercially.

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