Writing Your First WordPress Plugin: A Working Example

One file, one useful feature, and every fundamental you need: hooks, a meta box, nonces, capability checks, sanitising on input, escaping on output and cleaning up on uninstall.

Most introductions to plugin development stop at a file that prints hello world, which teaches you the header comment and nothing else. The useful version builds something small that you would actually keep, because the security and lifecycle details only appear once the plugin touches data.

We are going to build a last reviewed date. An editor sets a date on a post, and the post displays when it was last checked. It is genuinely useful on any site publishing factual content, and it exercises every fundamental.

Why a plugin and not the theme

The rule is worth restating because it decides the whole structure.

A theme controls presentation. A plugin controls functionality that must survive a theme change. Our feature stores data against posts, so if it lived in the theme, switching themes would orphan every review date in the database with nothing to read it.

Anything that creates or stores content belongs in a plugin. That is the boundary.

The file and the header

Create a folder in your plugins directory and a PHP file inside it. The header comment is what WordPress reads to list your plugin.

<?php
/**
 * Plugin Name: Last Reviewed Date
 * Description: Records and displays when a post was last fact-checked.
 * Version: 1.0.0
 * Author: Your Name
 * Text Domain: last-reviewed
 */

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

That last block is not optional. It stops the file executing if somebody requests it directly rather than through WordPress. Every plugin file should begin with it.

Hooks, which are the whole mental model

WordPress runs, and at defined moments it asks whether anybody wants to do something. Your plugin registers interest in those moments.

Actions are moments where you do something. Filters are moments where you receive a value and return a possibly modified one. That distinction is the entire model and once it is clear the rest follows.

We need three. One to add our editing interface, one to save what was entered, and one to modify the post content on output.

The editing interface

A meta box is a panel in the post editor. Register it on the hook that builds those panels.

add_action( 'add_meta_boxes', 'lrd_add_meta_box' );

function lrd_add_meta_box() {
    add_meta_box(
        'lrd_meta_box',
        'Last Reviewed',
        'lrd_render_meta_box',
        'post',
        'side'
    );
}

Then the function that draws it. Three things matter here: read the existing value, output a nonce, and escape everything you print.

function lrd_render_meta_box( $post ) {
    $value = get_post_meta( $post->ID, '_lrd_date', true );
    wp_nonce_field( 'lrd_save', 'lrd_nonce' );
    echo '<input type="date" name="lrd_date" value="'
        . esc_attr( $value ) . '" />';
}

The nonce is a token proving this form came from your editor rather than from somewhere else. Without it, anything that can make a logged-in editor’s browser submit a request can write to your posts.

The underscore prefix on the meta key hides it from the generic custom fields panel, which keeps the editor tidy.

Saving, and the three checks that matter

This is where most first plugins are insecure, and the pattern is always the same three checks before writing anything.

add_action( 'save_post', 'lrd_save_meta' );

function lrd_save_meta( $post_id ) {

    if ( ! isset( $_POST['lrd_nonce'] )
        || ! wp_verify_nonce( $_POST['lrd_nonce'], 'lrd_save' ) ) {
        return;
    }

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $date = isset( $_POST['lrd_date'] )
        ? sanitize_text_field( wp_unslash( $_POST['lrd_date'] ) )
        : '';

    if ( $date === '' ) {
        delete_post_meta( $post_id, '_lrd_date' );
        return;
    }

    update_post_meta( $post_id, '_lrd_date', $date );
}

Read those checks in order. Did this come from our form. Is this a real save rather than an autosave. Is this user actually allowed to edit this post. Only then do we touch the database.

Then sanitise on input. Note the unslashing before sanitising, because WordPress adds slashes to incoming data and skipping that step corrupts anything containing quotes.

Deleting the meta when the field is empty matters more than it looks. Without it you accumulate empty rows that your display code then has to guard against.

Displaying it

A filter receives the content and returns it with our line appended.

add_filter( 'the_content', 'lrd_append_date' );

function lrd_append_date( $content ) {

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

    $date = get_post_meta( get_the_ID(), '_lrd_date', true );

    if ( ! $date ) {
        return $content;
    }

    $shown = date_i18n(
        get_option( 'date_format' ),
        strtotime( $date )
    );

    return $content . '<p class="lrd">Last reviewed: '
        . esc_html( $shown ) . '</p>';
}

The guards at the top are the part beginners miss. Without them the filter runs on excerpts, on archive listings, on widgets and inside other queries, and your line appears in six places you did not intend.

Escaping on output is the counterpart to sanitising on input. Do both, every time, rather than reasoning about whether a particular value is trustworthy. The broader argument is in website security that protects your SEO.

Cleaning up on uninstall

The step almost every plugin skips, which is why WordPress databases accumulate metadata from plugins removed years ago.

Create a file named uninstall.php in your plugin folder. WordPress runs it when the plugin is deleted, not merely deactivated.

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

delete_post_meta_by_key( '_lrd_date' );

Deactivation should leave data alone, because people deactivate temporarily. Deletion is the explicit signal that it can go.

What to add next, in order

  1. Prefix everything. Function names, meta keys, option names. WordPress has one global namespace and a function called save_meta will collide with somebody eventually.
  2. Make strings translatable with the standard functions and your text domain.
  3. Expose it in the REST API by registering the meta, so the block editor and any API consumer can read and write it.
  4. Add it to structured data if the date is genuinely useful to publish, which for reviewed factual content it often is.
  5. Split into files once it grows past a couple of hundred lines, with the main file acting as a loader, the same discipline we apply to themes.

Finding out why it is not working

Your first plugin will fail silently at least once, and knowing where to look saves hours.

Turn on debugging in your local configuration so errors are reported rather than producing a blank page. A white screen is almost always a fatal error being hidden from you, and seeing the actual message takes you straight to the line.

When a hook appears not to fire, check three things in order. Is the file actually loaded, which you can confirm by putting a deliberate error at the top. Is the hook name spelled correctly, since a misspelled hook fails without complaint. And is your function registered before the hook runs, which matters for hooks that fire early.

When data is not saving, the usual culprits are the three checks. A failing nonce, a capability the current user does not have, or an autosave you returned from. Temporarily logging which check caused the return tells you immediately, and the answer is frequently that you were testing while logged in as a user without the capability.

When output appears in the wrong places, your filter guards are too loose. Add the singular, main query and in-loop checks and the problem usually disappears.

Test as a non-administrator before you consider it finished. Administrators have every capability, which means capability bugs are invisible to the person who wrote the code.

Versioning and sharing it

Once it works, a few habits make it maintainable rather than a file somebody is afraid to touch.

Keep the plugin in version control as its own folder, the same way you would a theme. Never edit it through the WordPress admin file editor, because the next deployment will overwrite the change and nobody will remember it was made there.

Bump the version number in the header on every release. It is how WordPress and any update mechanism know something changed, and it is how you work out which version a client is actually running when they report a problem.

Write a short readme in the folder covering what the plugin does, which hooks it uses, what data it stores and under which keys. Three paragraphs. The person reading it in two years may well be you, with no memory of the decisions.

If the plugin is for a client, decide deliberately whether it is a general-purpose plugin or a site-specific one. A site-specific plugin, named for that client, is the right home for all the small customisations that would otherwise accumulate in a theme. Many agencies maintain exactly one of these per client and it is a sound pattern.

What is a waste of effort

Building an options page before anybody has asked for a setting. Hard-code the decision and change it in code.

Loading assets on every page when your plugin only affects the editor or a single template. Enqueue conditionally.

Writing your own database table for something that fits in post meta. It fits far more often than people assume, and you have just taken on migrations and upgrades.

Copying a plugin boilerplate with twelve classes for a feature that is forty lines. Start small and add structure when the size demands it.

Skipping the nonce because it is your own site. It is exactly your own site that is being targeted.

A sensible build order

  1. Create the folder and file with a header and the direct-access guard.
  2. Add the meta box and confirm it appears in the editor.
  3. Add saving with the nonce, autosave and capability checks before anything else.
  4. Sanitise on input, escape on output.
  5. Add the display filter with proper guards.
  6. Add the uninstall file.
  7. Prefix everything and make strings translatable.
  8. Test as a non-administrator, which is where capability bugs appear.

Keep an eye on what your plugins cost the front end as the collection grows, which is the discipline in Core Web Vitals for WordPress without plugin overload.

We build plugins from scratch as part of the SEO and WordPress training in Pune, and if you would rather have one built for you, get in touch.