Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 68 ยท Plugins

Your First Plugin

Write your first WordPress plugin: the header comment, the ABSPATH guard, prefixing, hooks, mu-plugins and coding standards, with a runnable loader.

A plugin is a PHP file (or a folder of them) that WordPress loads on every request once it is activated. Plugins are how you add behavior that should stay when the theme changes: a custom post type, a shortcode, a contact form, an SEO tool. Everything a plugin does goes through hooks, the mechanism you met in Actions and Filters, so writing a plugin is mostly choosing the right hook and writing a careful callback.

This lesson builds the smallest useful plugin, explains the header comment that WordPress reads, the safety guard at the top of every file, the prefix rule that avoids name clashes, and the difference between normal plugins and must-use plugins. You need a working site first; see Setting Up a Local WordPress Site.

Where a plugin lives

Plugins go into wp-content/plugins/. The simplest plugin is one file there, but the usual form is a folder with a main file of the same name:

TEXT
wp-content/
  plugins/
    northwind-notice/
      northwind-notice.php    <- main file, has the header comment

WordPress scans every PHP file directly inside plugins/ and one level down into each folder, looking for the header comment. A file that has the header is listed in Plugins in wp-admin. Files deeper in a folder are never scanned for headers, which is why you put everything else in subfolders and require it from the main file.

The header comment

The plugin header is a PHP doc comment at the top of the main file. Only Plugin Name is required, but real plugins fill in more.

PHP
<?php
/**
 * Plugin Name:       Northwind Notice
 * Description:       Adds a short notice below every single post.
 * Version:           1.0.0
 * Requires at least: 6.4
 * Requires PHP:      7.4
 * Author:            Northwind Studio
 * License:           GPL-2.0-or-later
 * Text Domain:       northwind-notice
 */

Core reads these lines as Key: value pairs. Requires at least and Requires PHP stop activation on sites that cannot run the plugin. Text Domain ties the plugin to its translation files. Use a license compatible with WordPress, which is GPL-2.0-or-later or similar, if you plan to distribute the plugin.

The ABSPATH guard

PHP files in wp-content are reachable by URL. If someone visits /wp-content/plugins/northwind-notice/northwind-notice.php directly, the file would run without WordPress loaded, and any code at the top level could misbehave or leak errors. The standard defence is a one-line guard right after the header:

PHP
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

ABSPATH is a constant WordPress defines when it boots. If it is missing, the file was requested directly, so it quits at once. Put this guard in every PHP file that contains executable code.

Prefix everything

All plugins and themes share one global namespace for functions, constants, options and hook names. If your plugin defines function notice() and another plugin does too, PHP stops with a fatal "cannot redeclare" error. The cure is a unique prefix on every global: functions, classes without namespaces, constants, option names, post meta keys, hook names and script handles. A good prefix is short and specific to you, such as nwn_ for Northwind Notice. Namespaces (next lesson) reduce the problem for classes and functions, but option and hook names are strings, so they still need the prefix.

A complete first plugin

PHP
<?php
/**
 * Plugin Name: Northwind Notice
 * Description: Adds a short notice below every single post.
 * Version:     1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function nwn_append_notice( $content ) {
	if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
		return $content;
	}

	$notice = '<p class="nwn-notice">' . esc_html__( 'Thanks for reading!', 'northwind-notice' ) . '</p>';

	return $content . $notice;
}
add_filter( 'the_content', 'nwn_append_notice' );

Walk through it. The callback hooks the the_content filter, so it receives the post body as a string. The condition limits the change to single blog posts, inside the main loop of the main query, otherwise the notice would also appear in widgets, excerpts and other places that call the_content. It then returns the original content with the notice appended. A filter must always return a value, even when it changes nothing.

Copy this folder into wp-content/plugins/, open Plugins in wp-admin and press Activate. Open a post and the notice appears. Deactivate it and the notice vanishes; nothing in the database was changed because the plugin only filters output.

Activation in wp-admin

Activation does one main thing: WordPress adds the plugin's path to the active_plugins option. On every later request it reads that option and includes each listed file after core and before the theme. A fatal error in your file during activation makes WordPress refuse to activate the plugin and show the error. The sequence of loading is part of the bootstrap described in How WordPress Handles a Request.

flowchart LR
    A["WordPress boots<br/>wp-settings.php"] --> M["Load mu-plugins<br/>(always on)"]
    M --> P["Load active plugins<br/>(from active_plugins option)"]
    P --> H["Hook: plugins_loaded"]
    H --> T["Load the theme<br/>functions.php"]
    T --> I["Hook: init"]

Plugin files run before the theme, so plugin code should only register hooks at load time and wait for init to do real work.

The stand-in below acts like that loader. It is not WordPress code: it keeps a list of "files" with header comments in a string, parses the header with a regular expression, checks Requires PHP, refuses a file that has no Plugin Name, and then runs the plugin's registration code in the order the files are active.

PHP A plugin loader that reads headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real WordPress does the header parsing with get_file_data() and does not run the code of a file that lacks the header, it simply never lists it. The idea, header first and code afterwards, is the same.

Plugins versus must-use plugins

Besides wp-content/plugins/, WordPress has a second folder, wp-content/mu-plugins/ for must-use plugins. The differences matter in practice:

Normal plugin Must-use plugin
Folder wp-content/plugins/ wp-content/mu-plugins/
Activation Switched on and off in wp-admin Always on; no switch
Load order In the order of the active_plugins option Before normal plugins, alphabetically
Folders Scanned one level deep Only top-level PHP files load automatically
Updates Through the plugin updater Not updated automatically
Listed in wp-admin Plugins screen Separate "Must-Use" tab

Use a must-use plugin for site-specific code that nobody should be able to deactivate by mistake, such as a hosting company's caching integration. Because they have no activation step, activation hooks do not fire for them. For an ordinary plugin the activation and deactivation hooks exist; see Activation, Deactivation and Uninstall.

File naming and coding standards

Name the folder and the main file in lowercase with hyphens (northwind-notice/northwind-notice.php). The WordPress PHP coding standards differ from PSR-12 in some visible ways, and you will see them in all core code and most plugins:

  • Indent with tabs, not spaces.
  • Put spaces inside parentheses: if ( $x ), function nwn_run( $arg ).
  • Use Yoda conditions when comparing to a literal: if ( 'post' === $type ).
  • Use long array syntax array( ... ) in core style; short syntax is accepted by many modern projects.
  • Name functions in lowercase_with_underscores, classes in Capitalized_Words, files in lowercase-with-hyphens.

Tools such as PHP_CodeSniffer with the WordPress ruleset can check this automatically, and you will see them in Testing, Coding Standards and Deployment. The examples on this site sometimes use modern PHP in the runnable stand-ins; the real-code blocks follow the WordPress style.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which header is required for WordPress to recognize a file as a plugin?

    Only Plugin Name is required. The other headers are strongly recommended but optional.
  2. 2. Why does a plugin file start with if ( ! defined( 'ABSPATH' ) ) { exit; }?

    ABSPATH exists only when WordPress is running, so the guard exits if the file was requested without it.
  3. 3. Why do you prefix function and option names in a plugin?

    Two plugins defining the same function name cause a fatal error; a unique prefix avoids clashes.
  4. 4. Which statement about must-use plugins is true?

    Must-use plugins live in wp-content/mu-plugins/, load before normal plugins and cannot be deactivated from wp-admin.
  5. 5. What must a callback on the the_content filter always do?

    Filters pass a value along; returning nothing would erase the post body.

Summary

  • A plugin is a PHP file with a header comment, stored in wp-content/plugins/ and activated in wp-admin.
  • Only Plugin Name is required; Requires PHP, Version and Text Domain are strongly recommended.
  • Start every file with the ABSPATH guard and prefix all globals, including option and hook names.
  • Plugin files load before the theme, so register hooks at load time and do the work on later hooks.
  • Must-use plugins live in mu-plugins/, always run and have no activation step.
  • Follow the WordPress coding standards in real code: tabs, spaces inside parentheses, Yoda conditions.
  • The loader above is a stand-in, not core code.

Next up: Plugin Structure and Object-Oriented Plugins.