Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 68 ยท Real-World Projects

Project: An Events Plugin

Build an events plugin: a custom post type, a date meta box, an upcoming events query, a shortcode, REST output and a clean uninstall, with runnable stand-ins.

In this project you will build a small plugin called Acme Events. The site owner adds events in wp-admin with a title, a description and a date. Visitors see an "upcoming events" list wherever the shortcode [acme_events] is placed, and other programs can read the same list as JSON from the REST API. When the plugin is deleted, it removes its own data.

The plugin touches many earlier lessons: custom post types, meta boxes, meta queries, shortcodes, custom REST endpoints and activation and uninstall. Here you will wire them together into one coherent piece of software.

A plugin needs a real WordPress site, so the plugin files are read-only. The two runnable stand-ins reproduce the logic in plain PHP over SQLite: the upcoming query and shortcode, and the safe saving and cleanup. Dates are fixed in the examples so the output never changes.

Plan and file layout

Before writing code, decide what you store and how you will read it. An event is content with a title and a description, so it is a custom post type. The date is a small fact about one event, so it is post meta. Dates are stored as YYYY-MM-DD strings. That format sorts correctly as text and compares correctly as a DATE in a meta query, which is why it is the best choice.

TEXT
acme-events/
  acme-events.php        header, constants, loading
  includes/
    post-type.php        CPT and meta registration
    meta-box.php         date field and saving
    query.php            upcoming events helper
    shortcode.php        [acme_events]
    rest.php             /acme-events/v1/upcoming
  uninstall.php          removes events and options
flowchart LR
    A["Admin edits event"] --> B["Meta box saves<br/>_acme_event_date"]
    B --> C[("wp_posts + wp_postmeta")]
    C --> D["acme_get_upcoming_events()"]
    D --> E["Shortcode HTML"]
    D --> F["REST JSON"]

One query helper feeds both the shortcode and the REST endpoint, so they can never disagree.

Step 1: the main file and the post type

The main file has the plugin header, a guard against direct access, and loads the other files. Prefix everything with acme_ (see your first plugin).

PHP
<?php
/**
 * Plugin Name: Acme Events
 * Description: Lists upcoming events with a shortcode and a REST endpoint.
 * Version: 1.0.0
 * Requires at least: 6.4
 * Requires PHP: 7.4
 * License: GPL-2.0-or-later
 * Text Domain: acme-events
 */

defined( 'ABSPATH' ) || exit;

define( 'ACME_EVENTS_FILE', __FILE__ );
define( 'ACME_EVENTS_DIR', plugin_dir_path( __FILE__ ) );

require_once ACME_EVENTS_DIR . 'includes/post-type.php';
require_once ACME_EVENTS_DIR . 'includes/meta-box.php';
require_once ACME_EVENTS_DIR . 'includes/query.php';
require_once ACME_EVENTS_DIR . 'includes/shortcode.php';
require_once ACME_EVENTS_DIR . 'includes/rest.php';

register_activation_hook( __FILE__, function () {
    acme_register_event_post_type();
    flush_rewrite_rules();
} );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );

In includes/post-type.php register the type and its date field. The post type key acme_event is under the 20-character limit and prefixed to avoid clashes:

PHP
<?php
function acme_register_event_post_type(): void {
    register_post_type( 'acme_event', [
        'labels'       => [
            'name'          => __( 'Events', 'acme-events' ),
            'singular_name' => __( 'Event', 'acme-events' ),
            'add_new_item'  => __( 'Add New Event', 'acme-events' ),
        ],
        'public'       => true,
        'has_archive'  => true,
        'show_in_rest' => true,
        'menu_icon'    => 'dashicons-calendar-alt',
        'supports'     => [ 'title', 'editor', 'excerpt' ],
        'rewrite'      => [ 'slug' => 'events' ],
    ] );

    register_post_meta( 'acme_event', '_acme_event_date', [
        'type'              => 'string',
        'single'            => true,
        'show_in_rest'      => true,
        'sanitize_callback' => 'acme_sanitize_event_date',
        'auth_callback'     => function () {
            return current_user_can( 'edit_posts' );
        },
    ] );
}
add_action( 'init', 'acme_register_event_post_type' );

/**
 * Accept only a real date written as YYYY-MM-DD, otherwise store nothing.
 */
function acme_sanitize_event_date( $value ): string {
    $value = sanitize_text_field( (string) $value );
    $date  = DateTime::createFromFormat( '!Y-m-d', $value );

    return ( $date && $date->format( 'Y-m-d' ) === $value ) ? $value : '';
}

Registering the meta with show_in_rest and an auth_callback makes it appear in the standard REST response and lets the block editor save it (see custom fields and post meta). Note that the key starts with an underscore, which hides it from the generic "Custom Fields" box.

Step 2: the date meta box

A meta box renders one field and must be saved defensively: check the nonce, ignore autosaves, check the user's capability, then sanitize (see meta boxes and saving data).

PHP
<?php
add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'acme_event_details',
        __( 'Event details', 'acme-events' ),
        'acme_render_event_box',
        'acme_event',
        'side'
    );
} );

function acme_render_event_box( WP_Post $post ): void {
    $date = get_post_meta( $post->ID, '_acme_event_date', true );
    wp_nonce_field( 'acme_save_event', 'acme_event_nonce' );
    ?>
    <p>
        <label for="acme_event_date"><?php esc_html_e( 'Date', 'acme-events' ); ?></label><br>
        <input type="date" id="acme_event_date" name="acme_event_date"
               value="<?php echo esc_attr( $date ); ?>">
    </p>
    <?php
}

add_action( 'save_post_acme_event', function ( int $post_id ) {
    if ( ! isset( $_POST['acme_event_nonce'] )
        || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['acme_event_nonce'] ) ), 'acme_save_event' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $raw = isset( $_POST['acme_event_date'] ) ? wp_unslash( $_POST['acme_event_date'] ) : '';
    $date = acme_sanitize_event_date( $raw );

    if ( '' === $date ) {
        delete_post_meta( $post_id, '_acme_event_date' );
    } else {
        update_post_meta( $post_id, '_acme_event_date', $date );
    }
} );

The type="date" input already gives a calendar picker in most browsers, but you must still validate on the server, because anyone can send any value. The hook is save_post_acme_event, which only fires for this post type, so no extra post type check is needed.

Step 3: the upcoming events query

Put the query in one function, so every output uses it. It asks for events whose date is today or later, sorted from soonest to latest:

PHP
<?php
function acme_get_upcoming_events( int $limit = 5 ): array {
    $today = wp_date( 'Y-m-d' );

    $query = new WP_Query( [
        'post_type'              => 'acme_event',
        'post_status'            => 'publish',
        'posts_per_page'         => $limit,
        'no_found_rows'          => true,
        'meta_key'               => '_acme_event_date',
        'orderby'                => 'meta_value',
        'order'                  => 'ASC',
        'meta_query'             => [
            [
                'key'     => '_acme_event_date',
                'value'   => $today,
                'compare' => '>=',
                'type'    => 'DATE',
            ],
        ],
    ] );

    return $query->posts;
}

wp_date() uses the site's time zone, which matters: "today" for a visitor in the site's city must not flip at midnight UTC. no_found_rows skips counting total matches, because a short list has no pagination (see WP_Query in depth). Meta queries are not free (see performance optimization), but for hundreds of events this is perfectly fine, and the first stand-in below shows the same logic in SQL.

Step 4: the shortcode

PHP
<?php
add_shortcode( 'acme_events', function ( $atts ) {
    $atts = shortcode_atts( [ 'limit' => 5 ], $atts, 'acme_events' );
    $events = acme_get_upcoming_events( absint( $atts['limit'] ) );

    if ( ! $events ) {
        return '<p class="acme-events-empty">' . esc_html__( 'No upcoming events.', 'acme-events' ) . '</p>';
    }

    $html = '<ul class="acme-events">';
    foreach ( $events as $event ) {
        $date = get_post_meta( $event->ID, '_acme_event_date', true );
        $html .= sprintf(
            '<li><time datetime="%1$s">%2$s</time> <a href="%3$s">%4$s</a></li>',
            esc_attr( $date ),
            esc_html( wp_date( get_option( 'date_format' ), strtotime( $date ) ) ),
            esc_url( get_permalink( $event ) ),
            esc_html( get_the_title( $event ) )
        );
    }
    return $html . '</ul>';
} );

A shortcode must return its HTML, never echo it, and every value is escaped as late as possible, in the right context (see escaping output). Attributes arrive as untrusted strings, so absint() turns the limit into a safe integer.

A query and shortcode stand-in you can run

This stand-in stores events in SQLite, fixes "today" to a known date, and implements the same ideas: a date comparison, sorted ascending, a limit, a simple shortcode parser with default attributes, and escaped output.

PHP Upcoming events query and shortcode (stand-in)

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.

Check what is missing from the list: the draft is excluded by the status condition, and the event from 2030 is excluded by the date comparison. The title containing <Local> is printed as text because the output is escaped.

Step 5: REST output

There are two ways to expose events. Because the post type and the meta both have show_in_rest, WordPress already serves them at /wp-json/wp/v2/acme_event, with the date under meta. That is enough for the block editor and many clients. A small custom route can serve a cleaner, public "upcoming" feed built from the same helper:

PHP
<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'acme-events/v1', '/upcoming', [
        'methods'             => WP_REST_Server::READABLE,
        'permission_callback' => '__return_true', // Public data only.
        'args'                => [
            'limit' => [
                'type'              => 'integer',
                'default'           => 5,
                'minimum'           => 1,
                'maximum'           => 20,
                'sanitize_callback' => 'absint',
            ],
        ],
        'callback'            => function ( WP_REST_Request $request ) {
            $items = [];
            foreach ( acme_get_upcoming_events( $request['limit'] ) as $event ) {
                $items[] = [
                    'id'    => $event->ID,
                    'title' => get_the_title( $event ),
                    'date'  => get_post_meta( $event->ID, '_acme_event_date', true ),
                    'url'   => get_permalink( $event ),
                ];
            }
            return rest_ensure_response( $items );
        },
    ] );
} );

permission_callback is mandatory; '__return_true' is the honest way to say "this is public" (see custom REST endpoints). Only published events are returned, because the shared helper only asks for publish.

Step 6: uninstall cleanup

A well-behaved plugin removes its data only when it is deleted, not merely deactivated (see activation, deactivation and uninstall). Put this in uninstall.php:

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

$events = get_posts( [
    'post_type'      => 'acme_event',
    'post_status'    => 'any',
    'posts_per_page' => -1,
    'fields'         => 'ids',
] );

foreach ( $events as $event_id ) {
    wp_delete_post( $event_id, true ); // true skips the trash; meta goes with it.
}

delete_option( 'acme_events_version' );

Deleting through wp_delete_post() rather than raw SQL lets core remove meta, term links and comments properly. On a very large site you would delete in batches. Always consider whether the owner would be surprised: some plugins offer a setting "Delete data when uninstalling" and default it to off.

Saving and cleanup stand-in

The second stand-in covers the parts that protect your data: strict date validation, a nonce check, a capability check and the uninstall routine.

PHP Safe saving and uninstall cleanup (stand-in)

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.

Note that 2031-02-31 is rejected. Passing only a format check would accept it, but comparing the formatted result with the input catches dates that PHP would silently roll over into March.

Ideas to extend it

  • Add an end date and a location field, and show them in the list.
  • Add a block that wraps the shortcode logic (see dynamic blocks).
  • Add a past mode that lists previous events in reverse order.
  • Cache the upcoming list in a transient and clear it in a save_post_acme_event hook.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store the event date as YYYY-MM-DD?

    The year-first format is ordered the same alphabetically and chronologically, so sorting and comparison work without conversion.
  2. 2. What must a shortcode callback do with its HTML?

    Shortcodes are replaced inside the content, so the callback must return a string. Echoing would print it in the wrong place.
  3. 3. Why is uninstall.php better than the deactivation hook for deleting event data?

    People deactivate plugins to troubleshoot. Deleting their content then would be a nasty surprise, so data removal belongs in uninstall.
  4. 4. Why does the saving code compare the formatted date with the input?

    DateTime can accept an overflowing day and turn it into the next month. Formatting it back and comparing exposes that change.

Summary

  • Events are a custom post type with a YYYY-MM-DD date in post meta, registered with show_in_rest and a sanitize callback.
  • The meta box saves only after a nonce check, an autosave check and a capability check, then validates the date strictly.
  • One helper, acme_get_upcoming_events(), powers both the shortcode and the REST endpoint.
  • Shortcodes return escaped HTML; REST routes declare a permission_callback and validated args.
  • uninstall.php removes content and options through core functions, and only runs when the plugin is deleted.
  • The runnable code is a plain-PHP stand-in, not real WordPress.

Next: Project: A Secure Contact Form Plugin