WordPress Plugin Development: The Complete Guide to Building Your First Plugin

register_setting's third parameter is an args array whose sanitize_callback cleans values before saving. Build a full plugin: header, hooks, nonces, a block.

Plugin folder tree for Simple Note Manager with main file, uninstall.php, includes and build folders beside the heading Build your first plugin

The third parameter of register_setting() is an array of arguments, and its sanitize_callback key is where you name the function that cleans a value before WordPress saves it. The array form (type, description, sanitize_callback, show_in_rest, default) has existed since WordPress 4.7. Older tutorials pass a bare callback string such as 'intval' in that slot. That still works today because core checks whether the argument is callable and wraps it for you, but the array is the documented form. We checked this against the developer.wordpress.org reference on 15 November 2026.

This guide takes you through a full small plugin, Simple Note Manager, in the order a real plugin grows: the header, a safe main file, activation, deactivation and uninstall, hooks, the Settings API, a shortcode, nonces, capability checks and escaping, translation, one block made with create-block, and a Plugin Check run before you ship. Every PHP snippet below passed php -l on PHP 8.5 and is marked “checked on 15 Nov 2026”.

What does the third parameter of register_setting do?

It tells WordPress how to treat the option you named in the second parameter. The first parameter is the settings group your form posts to, the second is the option name stored in the wp_options table, and the third carries everything else. Before 4.7 the third slot held only a sanitize callback. After 4.7 it holds an array, which lets the same call describe the value for the REST API too.

These are the keys that matter, taken from the function reference and the 4.7 developer note:

Key

Default

What it does

type

'string'

Data type: string, boolean, integer, number, array or object. Mainly used by the REST API.

description

empty

Human-readable text, used by the REST API.

sanitize_callback

null

Function run on the value before it is saved. Core attaches it to the sanitize_option_{option_name} filter.

show_in_rest

false

Expose the setting at /wp/v2/settings. Array-type settings need a schema with items.

default

none

Returned by get_option() when nothing is stored.

label

empty

A label for the data. Added in WordPress 6.6.

The full call looks like the code below. Notice that we register on init, not only on admin_init: a REST request never fires admin_init, so a setting registered only there would be missing from the REST settings endpoint.

Checked on 15 Nov 2026 against developer.wordpress.org.

<?php
add_action( 'init', 'snm_register_settings' );
add_action( 'admin_menu', 'snm_add_settings_page' );

function snm_register_settings(): void {
	register_setting(
		'snm_settings_group',
		'snm_per_page',
		array(
			'type'              => 'integer',
			'description'       => __( 'How many notes the shortcode shows.', 'simple-note-manager' ),
			'sanitize_callback' => 'snm_sanitize_per_page',
			'show_in_rest'      => true,
			'default'           => 5,
		)
	);

	register_setting(
		'snm_settings_group',
		'snm_heading',
		array(
			'type'              => 'string',
			'description'       => __( 'Heading above the notes list.', 'simple-note-manager' ),
			'sanitize_callback' => 'sanitize_text_field',
			'show_in_rest'      => true,
			'default'           => 'Notes',
		)
	);
}

function snm_sanitize_per_page( $value ): int {
	return min( 50, max( 1, absint( $value ) ) );
}

function snm_add_settings_page(): void {
	add_options_page(
		__( 'Simple Note Manager', 'simple-note-manager' ),
		__( 'Note Manager', 'simple-note-manager' ),
		'manage_options',
		'snm-settings',
		'snm_render_settings_page'
	);
}

function snm_render_settings_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		<form action="options.php" method="post">
			<?php settings_fields( 'snm_settings_group' ); ?>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><label for="snm_heading"><?php esc_html_e( 'Heading', 'simple-note-manager' ); ?></label></th>
					<td><input type="text" id="snm_heading" name="snm_heading" class="regular-text"
						value="<?php echo esc_attr( get_option( 'snm_heading' ) ); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><label for="snm_per_page"><?php esc_html_e( 'Notes to show', 'simple-note-manager' ); ?></label></th>
					<td><input type="number" id="snm_per_page" name="snm_per_page" min="1" max="50"
						value="<?php echo esc_attr( get_option( 'snm_per_page' ) ); ?>"></td>
				</tr>
			</table>
			<?php submit_button(); ?>
		</form>
	</div>
	<?php
}

How does the sanitize callback for a setting work?

When someone saves your options form, options.php calls update_option(), and that runs the value through sanitize_option(). Core hooks your sanitize_callback onto the sanitize_option_{option_name} filter, so the callback receives the raw submitted value and must return the cleaned one. Return something wrong and that wrong value is what gets saved. The callback is a filter, not a validator: it cannot show an error by itself. If you need to tell the user “that number was too large”, call add_settings_error() inside it.

Pick the sanitizer by the kind of value, not by habit. In the example above the page-count setting goes through our own small function that forces an integer between 1 and 50, and the heading goes straight through sanitize_text_field(). Core registers the callback with a single accepted argument, so any one-argument function works as a callback name. A function that needs the option name or the old value has to read it another way.

One quirk catches almost everyone. On the very first save, when the option does not exist yet, update_option() can run the sanitize callback twice, and the second pass receives the output of the first. That is long-standing Trac ticket #21989, still open when we checked. A callback that only trims or casts does not care. A callback that encrypts or appends something does, so keep sanitizers idempotent: running them on their own output must change nothing.

Which sanitizer fits which value?

Value

Sanitize on the way in

Escape on the way out

Single line of text

sanitize_text_field()

esc_html() or esc_attr()

Text with some HTML

wp_kses_post()

wp_kses_post()

Email

sanitize_email()

esc_html()

Whole number, never negative

absint()

esc_html() or (int)

URL you store

esc_url_raw()

esc_url()

Value from a fixed list

Compare with in_array( $v, $allowed, true )

esc_html()

The rule behind the table is old and still right: sanitize when data enters, escape when data leaves. They are different jobs. Sanitizing does not make a value safe to print, and escaping does not make a value fit to store.

What goes in the plugin header?

Only Plugin Name is required, according to the plugin handbook, but a plugin you plan to share should carry the full set. WordPress reads this comment block to list the plugin on the Plugins screen and to decide whether the site can run it.

Checked on 15 Nov 2026 against the header requirements page.

<?php
/**
 * Plugin Name:       Simple Note Manager
 * Plugin URI:        https://example.com/simple-note-manager
 * Description:       Stores short notes and shows them with a shortcode.
 * Version:           1.0.0
 * Requires at least: 6.5
 * Requires PHP:      8.1
 * Author:            Your Name
 * Author URI:        https://example.com
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       simple-note-manager
 * Domain Path:       /languages
 */

defined( 'ABSPATH' ) || exit;

define( 'SNM_VERSION', '1.0.0' );
define( 'SNM_FILE', __FILE__ );

Four fields do real work beyond display. Requires at least and Requires PHP stop the plugin from activating on sites that cannot run it. Text Domain and Domain Path tell WordPress where your translations live; the text domain should match your plugin folder name. The line after the comment matters too: defined( 'ABSPATH' ) || exit; stops anyone from loading the file directly by its URL.

We set Requires PHP: 8.1 because that is a sensible floor for new code in 2026. WordPress.org currently recommends PHP 8.3 or newer. Our guide to PHP 8.3 features for WordPress developers shows what you gain by raising the floor.

How do I make my plugin depend on another plugin?

Add a Requires Plugins line to the header. The header arrived in WordPress 6.5 (the dev note is dated 5 March 2024). It takes a comma-separated list of WordPress.org slugs:

 * Requires Plugins:  woocommerce, advanced-custom-fields

The rules from the handbook and the 6.5 dev note are short. Use the slug, never folder/file.php. Your plugin cannot be installed before its dependencies and cannot be activated until they are active. A dependency cannot be deactivated while your plugin is active. If your plugin is hosted on WordPress.org, it can only list dependencies hosted there too. There are no version constraints and no load-order guarantee, so keep using class_exists() or function_exists() guards before you call into the other plugin. Under WP-CLI, wp plugin activate --all may need to run twice because a dependent cannot activate before its dependencies are on.

How should I structure the main plugin file?

Keep the main file small. Its jobs are the header, the direct-access guard, a few constants, and loading everything else. A first plugin can keep all code in that one file; once you pass roughly 300 lines, move each concern into its own file under includes/ and require_once them from the main file.

Prefix everything global. Functions, constants, option names, post type slugs, hook names you invent, and shortcode tags all live in one shared namespace with every other plugin on the site. Our example uses snm_ for all of them. Classes and namespaces are a fine alternative, and they are what you will want as the plugin grows. For a plugin this size, plain prefixed functions are easier to read and carry no cost.

Here is the custom post type that holds the notes. We keep the notes in a post type, not a hand-made table, so WordPress gives us the admin screens, revisions, REST routes and capabilities for free. If you do need your own table later, read our guide to writing safe and fast database queries with wpdb first, and our custom post types tutorial goes deeper on this registration call.

Checked on 15 Nov 2026.

<?php
add_action( 'init', 'snm_register_note_type' );

function snm_register_note_type(): void {
	register_post_type(
		'snm_note',
		array(
			'labels'       => array(
				'name'          => __( 'Notes', 'simple-note-manager' ),
				'singular_name' => __( 'Note', 'simple-note-manager' ),
			),
			'public'       => false,
			'show_ui'      => true,
			'show_in_rest' => true,
			'supports'     => array( 'title', 'editor' ),
			'menu_icon'    => 'dashicons-edit',
		)
	);
}

What belongs in activation, deactivation and uninstall?

Activation sets up, deactivation pauses, and uninstall removes. The mistake we see most is mixing them: deleting data on deactivation, so a user who switches the plugin off for a conflict test loses their settings. The handbook is direct about it: deactivation hooks are for temporary work like flushing rewrite rules, and cleanup of options and tables belongs to the uninstall path.

Event

Do

Do not

Activation

Add default options with add_option(), create tables, flush rewrite rules after registering post types

Output anything, even a space

Deactivation

Flush rewrite rules, unschedule cron events

Delete options, tables or content

Uninstall

Delete options, drop your own tables, remove transients

Delete the site owner’s content without asking them

The activation and deactivation hooks go in the main plugin file, because register_activation_hook() needs the path to that file:

Checked on 15 Nov 2026.

<?php
register_activation_hook( SNM_FILE, 'snm_activate' );
register_deactivation_hook( SNM_FILE, 'snm_deactivate' );

function snm_activate(): void {
	// Defaults only. add_option() leaves an existing value alone on re-activation.
	add_option( 'snm_per_page', 5 );
	add_option( 'snm_heading', __( 'Notes', 'simple-note-manager' ) );

	// Rewrite rules need the post type registered first.
	snm_register_note_type();
	flush_rewrite_rules();
}

function snm_deactivate(): void {
	// Temporary things only: rewrite rules and scheduled events. No data deletion here.
	flush_rewrite_rules();
}

Note that the activation function calls the post type registration directly before flush_rewrite_rules(). The init hook has not run yet during activation, so without that call the flush would not know your post type exists. Flushing rewrite rules is expensive; do it on activation and deactivation only, never on every page load.

Uninstall has two methods. You can call register_uninstall_hook() from the main file, or you can ship an uninstall.php file in the plugin root. WordPress runs the file when the user deletes the plugin from the admin, after deactivating it. The file must start with the WP_UNINSTALL_PLUGIN check, which WordPress defines only during a real uninstall; without the check, anyone who requests the file’s URL directly could trigger your cleanup code. That constant is not defined when you use register_uninstall_hook(), so the check applies to the file method only.

Checked on 15 Nov 2026. This is the whole file.

<?php
// Runs only when WordPress deletes the plugin from the admin.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

delete_option( 'snm_per_page' );
delete_option( 'snm_heading' );

// Multisite: delete_site_option( 'snm_network_flag' ); for network-wide options.
// Notes are the site owner's content, so this plugin leaves them in place on purpose.

On multisite, options saved per site live in each site’s own table. Looping through every site in an uninstall can be heavy on a large network, so the handbook warns about doing it carelessly.

How do WordPress hooks work in a plugin?

Hooks are named points in WordPress where your code can attach. An action runs your function at that point and ignores what it returns. A filter passes a value through your function, and you must return the value, changed or not. Both use the same registration pattern: add_action( $hook, $callback, $priority, $accepted_args ) and add_filter() with the same arguments. Priority defaults to 10, and lower numbers run first. $accepted_args defaults to 1, so a filter that receives two arguments must ask for 2.

Three actions cover most first plugins. plugins_loaded fires once all active plugins are loaded, so it is the place to check for another plugin. init is where you register post types, taxonomies, settings, shortcodes and blocks. admin_menu is where you add admin pages. If you ever wonder why your code runs too early or too late, our reference on the order WordPress hooks fire lays out the sequence.

Two habits keep hooks maintainable. Hook named functions, not anonymous ones, in code other people may extend: another developer can call remove_action() on a named callback and cannot on a closure. And never edit core files or another plugin’s files to change behaviour. If a hook you need does not exist, look at its neighbours before assuming that; the filter or action usually sits one step away.

How do I add a settings page with the Settings API?

You already saw the registration half in the code near the top. The page half uses add_options_page() to place a screen under the Settings menu, and a form that posts to options.php. Inside the form, settings_fields( 'snm_settings_group' ) prints a hidden nonce field and the option-page fields that core needs. When the form posts, core checks that nonce and the user’s capability, runs each registered sanitize callback, and saves the options. You do not write a save handler at all.

Three details trip people up. The group name you pass to settings_fields() must match the first parameter of register_setting(). The name attribute of each input must match the registered option name exactly. And the capability on add_options_page() controls who sees the menu, while the page callback should still check current_user_can() itself, as ours does, so a direct request cannot slip past.

Reading a value back is one line: get_option( 'snm_per_page' ). Because we registered a default, the call returns 5 even before anyone has saved the form.

How do I build a shortcode that is safe to output?

A shortcode callback receives the attributes as an array and must return a string. If it echoes, the output lands at the top of the page instead of where the shortcode sits. Merge the user’s attributes with defaults through shortcode_atts(), validate them, and escape every value you print.

Checked on 15 Nov 2026.

<?php
add_shortcode( 'simple_notes', 'snm_shortcode' );

function snm_shortcode( $atts ): string {
	$atts = shortcode_atts(
		array( 'limit' => (int) get_option( 'snm_per_page', 5 ) ),
		$atts,
		'simple_notes'
	);

	$query = new WP_Query(
		array(
			'post_type'              => 'snm_note',
			'posts_per_page'         => min( 50, max( 1, absint( $atts['limit'] ) ) ),
			'no_found_rows'          => true,
			'update_post_term_cache' => false,
		)
	);

	if ( ! $query->have_posts() ) {
		return '';
	}

	$html = '<div class="snm-notes"><h2>' . esc_html( get_option( 'snm_heading', 'Notes' ) ) . '</h2><ul>';
	foreach ( $query->posts as $note ) {
		$html .= '<li>' . esc_html( get_the_title( $note ) ) . '</li>';
	}
	$html .= '</ul></div>';

	return $html;
}

The query passes no_found_rows because we never paginate, which skips a costly count query. We also cap the limit at 50, so a visitor cannot ask a page to load every note on a big site by editing a shortcode attribute. Output goes through esc_html() on both the heading and each title.

What are nonces, and when do I need a capability check as well?

A nonce is a short-lived token tied to a user and an action. It proves a request came from a page your plugin rendered, not from a forged link on another site. It does not prove the user is allowed to do the thing. A subscriber can obtain a valid nonce for many actions, so every privileged handler needs both checks: current_user_can() for permission, then check_admin_referer() or wp_verify_nonce() for origin.

The Settings API did both for you in the previous section. For your own handlers, such as a “clear all notes” button, you do it by hand. This form posts to admin-post.php, and the handler runs on the admin_post_{action} hook:

Checked on 15 Nov 2026.

<?php
add_action( 'admin_post_snm_clear_notes', 'snm_handle_clear_notes' );

function snm_clear_notes_form(): void {
	?>
	<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
		<input type="hidden" name="action" value="snm_clear_notes">
		<?php wp_nonce_field( 'snm_clear_notes', 'snm_nonce' ); ?>
		<?php submit_button( __( 'Move all notes to trash', 'simple-note-manager' ), 'delete' ); ?>
	</form>
	<?php
}

function snm_handle_clear_notes(): void {
	// 1. Who is asking? 2. Did the request come from our form?
	if ( ! current_user_can( 'delete_others_posts' ) ) {
		wp_die( esc_html__( 'You are not allowed to do this.', 'simple-note-manager' ), 403 );
	}
	check_admin_referer( 'snm_clear_notes', 'snm_nonce' );

	$ids = get_posts(
		array(
			'post_type'      => 'snm_note',
			'posts_per_page' => 200,
			'fields'         => 'ids',
		)
	);
	foreach ( $ids as $id ) {
		wp_trash_post( $id );
	}

	wp_safe_redirect( add_query_arg( 'snm_cleared', count( $ids ), admin_url( 'options-general.php?page=snm-settings' ) ) );
	exit;
}

The same pairing applies to AJAX handlers and REST routes. For REST, the equivalent of the capability check is a permission_callback on the route, and a missing one is the first thing reviewers flag. Our guide on REST API authentication covers cookies, application passwords and nonce headers for that side.

How do I make a plugin translatable?

Wrap each visible string in a translation function with your text domain: __() returns the string, _e() echoes it, esc_html__() and esc_html_e() translate and escape in one step, and _n() picks singular or plural from a count. Add a /* translators: */ comment above any string with a placeholder so translators know what it stands for. The text domain must be a plain string, not a constant or variable, because the tools that extract strings read your code without running it.

Checked on 15 Nov 2026.

<?php
$count = 3;

/* translators: %d: number of notes. */
$label = _n( '%d note', '%d notes', $count, 'simple-note-manager' );

echo esc_html( sprintf( $label, $count ) );
echo esc_html__( 'Add note', 'simple-note-manager' );

Two timing rules changed over the years. Since WordPress 4.6, a plugin hosted on WordPress.org no longer needs load_plugin_textdomain(); WordPress loads the translations itself. Since 6.7, WordPress warns when a translation function runs before init. That is why every __() call in our example sits inside a function that runs on init or later, and never at the top level of the file. If you distribute outside WordPress.org, you still call load_plugin_textdomain(), and you call it on init or later.

How do I add a block to my plugin with create-block?

Let the official scaffolding tool write the boilerplate. The block editor handbook gives this command, and the tool needs Node 22.13 or newer as of our check:

npx @wordpress/create-block@latest simple-note-manager
cd simple-note-manager
npm start

npm start runs the development build with file watching. When you are ready to test or ship, run npm run build to produce the optimised files under build/. The tool creates a complete block plugin, so move the generated block folder into your own plugin if you want it beside your settings code. Add --variant dynamic to start from a dynamic block, whose output is rendered by PHP on each request. That suits a note list, because the notes change without anyone editing the page.

Each block is described by a block.json file. A trimmed version for our dynamic block looks like this:

Checked on 15 Nov 2026 against the block metadata reference.

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "simple-note-manager/note-list",
	"title": "Note List",
	"category": "widgets",
	"icon": "edit",
	"description": "Shows the latest notes.",
	"textdomain": "simple-note-manager",
	"editorScript": "file:./index.js",
	"render": "file:./render.php"
}

apiVersion 3 is the current version and arrived in WordPress 6.3. The render key points at a PHP file that receives $attributes, $content and $block, and it has worked since WordPress 6.1. When a block is registered from PHP, WordPress registers the scripts and styles listed in block.json for you. Registration is one call in your main plugin file, pointed at the folder that holds the built block.json:

<?php
add_action( 'init', 'snm_register_block' );

function snm_register_block(): void {
	// block.json sits in the folder npm run build produced.
	register_block_type( __DIR__ . '/build' );
}

Write the block’s edit component and its PHP render output with the same escaping rules as the shortcode above: anything that reaches the front end through render.php still needs esc_html() and friends.

How do I check a plugin with Plugin Check before I ship?

Install the Plugin Check plugin from WordPress.org. It is the tool the plugin review team points authors to, and it runs most of the checks applied to new directory submissions, plus best-practice checks for internationalisation, accessibility, performance and security. When we looked on 15 November 2026 the listing showed version 2.2.0 and more than 10,000 active installations.

Run it from Tools > Plugin Check in the admin and pick your plugin, or from the command line:

wp plugin check simple-note-manager

By default the command runs static checks only. Runtime checks need the checker’s cli.php file loaded with WP-CLI’s --require argument, as the plugin’s own description explains. Passing every check in the plugin repository category is what a directory submission typically needs, though a clean run does not guarantee approval, since human reviewers still read the code. Fix every error. Read each warning and decide, because some are advice for cases that do not apply to you.

Do I need PHPUnit as well?

Plugin Check finds standards problems. It does not tell you whether your logic works. Write tests for the pure functions first: snm_sanitize_per_page() is a good start because it has clear inputs and outputs, and each branch (negative, zero, huge, non-numeric) is a one-line test. Add integration tests with the WordPress test suite when you have queries and hooks worth guarding. A manual pass remains worthwhile: activate, deactivate, reactivate, save the settings form with odd input, and view the page source to confirm output is escaped.

Common mistakes people report

These problems come up repeatedly in the WordPress.org forums, on Trac and in the official handbook warnings. We checked each link on 15 November 2026.

  • A sanitize callback that runs twice on the first save. People who encrypt or append text in the callback find the value changed twice, because update_option() can sanitize twice when the option does not exist yet. See Trac #21989. Fix: keep the callback idempotent.
  • “The plugin generated N characters of unexpected output during activation.” Stray whitespace after a closing PHP tag, an echo or a notice during activation causes it, and it often appears with WP_DEBUG on. See this forum thread. Fix: omit the closing PHP tag in pure PHP files and never output from activation code.
  • A setting that never shows up in the REST API. show_in_rest defaults to false, array-type settings need a schema with items, and registering only on admin_init hides it from REST requests. See the register_setting reference.
  • A dependency written as a file path. Requires Plugins wants a WordPress.org slug; folder/file.php is not supported. See the header requirements page.
  • Translations loaded too early. Since WordPress 6.7, calling a translation function before init triggers a notice. See the 6.7 i18n dev note.
  • Deleting data on deactivation, or skipping the uninstall guard. Both are warned against in the uninstall methods handbook page.

Frequently asked questions

Is a string still allowed as the third argument of register_setting?

Yes. Core detects a callable and treats it as the sanitize callback, and the reference page does not mark this as deprecated. Use the array form anyway, since it is the documented one and the only way to set type, default or show_in_rest.

Do I need to sanitize an option that only admins can change?

Yes. Admin accounts get phished, and a sanitized option cannot carry a script into your front end later. The cost is one function name.

Does the sanitize callback run if I save with update_option directly?

Yes. update_option() applies the sanitize_option_{option_name} filter, so a registered callback runs whether the save came from the settings form, the REST API or your own code.

Should I use a class or plain functions?

Either is fine. Plain prefixed functions are simplest for a small plugin. Move to namespaced classes with an autoloader when the plugin passes a few files and you want the structure to be explicit.

Which PHP version should a new plugin support?

Set the floor by who will install it. We use 8.1 in this tutorial; WordPress.org recommends 8.3 or newer for sites.

What to do next

Build the plugin above on a local site and break it on purpose: save a negative number, submit the clear form without the nonce, deactivate and reactivate, then delete the plugin and check that the options are gone from wp_options. Then run Plugin Check, and fix what it reports before you submit anything to the directory.

Varun Dubey

Written by

Varun Dubey

Varun Dubey runs Wbcom Designs, the WordPress studio he founded in India in 2009. He has spent sixteen years building on WordPress and BuddyPress, shipping client work and products such as Reign, BuddyX, Jetonomy and MediaVerse, and has been putting Claude and OpenAI workflows into production since 2023. He writes up what the studio learns along the way.

More about Varun

No comments yet