Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 68 ยท Real-World Projects

Project: A Reading List with REST and Blocks

Build a reading list plugin: a books post type with meta, a custom REST endpoint, a server-rendered dynamic block, and a settings page for options.

This project builds a reading list plugin called Acme Reading. You track books with an author, a reading status and a rating. A custom REST endpoint lists books and lets an editor change a book's status. A dynamic block shows the list on any page, rendered by PHP so it is always current. A settings page controls defaults such as how many books to show. Together these pieces are a compact tour of how modern WordPress plugins are put together.

You will use custom post types, custom fields, custom REST endpoints, dynamic blocks and the Settings API. If any of them feels unfamiliar, skim that lesson first.

The plugin needs WordPress, so its files are read-only. The runnable stand-ins implement the endpoint rules (routing, validation, permissions) and the block render in plain PHP. Block editor JavaScript is shown but not run, because it needs the WordPress packages and a build step.

Architecture

flowchart LR
    S["Settings page<br/>option: acme_reading_settings"] --> B["Dynamic block<br/>render.php"]
    P[("Books: acme_book<br/>+ meta")] --> B
    P --> R["REST: /acme-reading/v1/books"]
    R --> C["Editor or app<br/>updates status"]
    C --> P

Books are stored once. The block and the REST endpoint both read them, and the settings option sets defaults.

TEXT
acme-reading/
  acme-reading.php
  includes/
    post-type.php
    rest.php
    settings.php
  blocks/reading-list/
    block.json
    render.php
    index.js          (editor script, built with @wordpress/scripts)

Step 1: books and their meta

A book has a title (the post title), and three small facts. Register them as meta with types, defaults and sanitizing, and expose them to REST:

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

function acme_reading_statuses(): array {
    return [ 'to-read', 'reading', 'finished' ];
}

add_action( 'init', function () {
    register_post_type( 'acme_book', [
        'labels'       => [
            'name'          => __( 'Books', 'acme-reading' ),
            'singular_name' => __( 'Book', 'acme-reading' ),
        ],
        'public'       => true,
        'show_in_rest' => true,
        'menu_icon'    => 'dashicons-book',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'custom-fields' ],
        'rewrite'      => [ 'slug' => 'books' ],
    ] );

    $auth = function () {
        return current_user_can( 'edit_posts' );
    };

    register_post_meta( 'acme_book', 'acme_author', [
        'type'              => 'string',
        'single'            => true,
        'show_in_rest'      => true,
        'sanitize_callback' => 'sanitize_text_field',
        'auth_callback'     => $auth,
    ] );
    register_post_meta( 'acme_book', 'acme_status', [
        'type'              => 'string',
        'single'            => true,
        'default'           => 'to-read',
        'show_in_rest'      => true,
        'sanitize_callback' => function ( $value ) {
            return in_array( $value, acme_reading_statuses(), true ) ? $value : 'to-read';
        },
        'auth_callback'     => $auth,
    ] );
    register_post_meta( 'acme_book', 'acme_rating', [
        'type'              => 'integer',
        'single'            => true,
        'default'           => 0,
        'show_in_rest'      => true,
        'sanitize_callback' => function ( $value ) {
            return max( 0, min( 5, (int) $value ) );
        },
        'auth_callback'     => $auth,
    ] );
} );

Note that the post type supports custom-fields and the meta uses show_in_rest. That combination is what lets the block editor read and write the values. Without a leading underscore, the keys are not protected, which is why auth_callback matters: it says who may change them through REST (see custom fields and post meta).

Step 2: a custom REST endpoint

WordPress already exposes books at /wp-json/wp/v2/acme_book. A custom route is worth adding when you want a shaped response (only what clients need), a domain-specific action ("mark as finished") or different permissions. This route has two endpoints: a public list and a protected status update.

PHP
<?php
add_action( 'rest_api_init', function () {

    register_rest_route( 'acme-reading/v1', '/books', [
        'methods'             => WP_REST_Server::READABLE,
        'permission_callback' => '__return_true',
        'args'                => [
            'status' => [
                'type'    => 'string',
                'enum'    => array_merge( [ 'all' ], acme_reading_statuses() ),
                'default' => 'all',
            ],
            'per_page' => [
                'type'    => 'integer',
                'default' => 10,
                'minimum' => 1,
                'maximum' => 50,
            ],
        ],
        'callback'            => 'acme_rest_list_books',
    ] );

    register_rest_route( 'acme-reading/v1', '/books/(?P<id>\d+)/status', [
        'methods'             => WP_REST_Server::EDITABLE,
        'permission_callback' => function ( WP_REST_Request $request ) {
            return current_user_can( 'edit_post', (int) $request['id'] );
        },
        'args'                => [
            'id'     => [ 'type' => 'integer', 'required' => true ],
            'status' => [
                'type'     => 'string',
                'required' => true,
                'enum'     => acme_reading_statuses(),
            ],
        ],
        'callback'            => 'acme_rest_update_status',
    ] );
} );

function acme_book_to_array( WP_Post $post ): array {
    return [
        'id'     => $post->ID,
        'title'  => get_the_title( $post ),
        'author' => (string) get_post_meta( $post->ID, 'acme_author', true ),
        'status' => (string) get_post_meta( $post->ID, 'acme_status', true ),
        'rating' => (int) get_post_meta( $post->ID, 'acme_rating', true ),
    ];
}

function acme_rest_list_books( WP_REST_Request $request ): WP_REST_Response {
    $args = [
        'post_type'      => 'acme_book',
        'post_status'    => 'publish',
        'posts_per_page' => $request['per_page'],
        'orderby'        => 'title',
        'order'          => 'ASC',
    ];
    if ( 'all' !== $request['status'] ) {
        $args['meta_query'] = [ [ 'key' => 'acme_status', 'value' => $request['status'] ] ];
    }

    $books = array_map( 'acme_book_to_array', ( new WP_Query( $args ) )->posts );
    return rest_ensure_response( $books );
}

function acme_rest_update_status( WP_REST_Request $request ) {
    $post = get_post( (int) $request['id'] );
    if ( ! $post || 'acme_book' !== $post->post_type ) {
        return new WP_Error( 'acme_not_found', __( 'Book not found.', 'acme-reading' ), [ 'status' => 404 ] );
    }
    update_post_meta( $post->ID, 'acme_status', $request['status'] );
    return rest_ensure_response( acme_book_to_array( $post ) );
}

The pieces to notice:

  • permission_callback is required. The list is public (__return_true, meaning "anyone"); the update checks the capability for that specific post with edit_post.
  • args do validation for you. enum, minimum and maximum are checked before your callback runs, and a bad value returns a 400 response. You do not need an if for them.
  • Errors are WP_Error objects with an HTTP status in the data.
  • The method EDITABLE covers POST, PUT and PATCH. Calls from JavaScript on a logged-in page need the REST nonce header X-WP-Nonce, which WordPress script helpers provide; otherwise the request counts as logged out.

From the command line (read-only):

Terminal
curl "https://example.com/wp-json/acme-reading/v1/books?status=reading&per_page=3"

The endpoint rules, runnable

This stand-in is a mini router that applies the same ideas: routes with a pattern, argument checks against a schema (enum, minimum, maximum, required), a permission check that runs before the callback, and JSON results with status codes.

PHP A mini router with validation and permissions (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.

Real WordPress uses 401 for logged-out users and 403 for logged-in users who lack the capability; this stand-in always answers 401 to keep things short. The order of the checks is the part to remember: permission, then argument validation, then your code.

Step 3: a dynamic block

A dynamic block saves no HTML in the post. The post stores only a comment with the block's attributes, and PHP builds the markup each time the page is rendered. That is the right choice for lists that change, such as this reading list, because you never have stale HTML saved inside old posts (see dynamic blocks).

The block is described by block.json:

JSON
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "acme/reading-list",
  "title": "Reading List",
  "category": "widgets",
  "icon": "book",
  "description": "Shows books from your reading list.",
  "attributes": {
    "status": { "type": "string", "default": "all" },
    "count": { "type": "number", "default": 5 },
    "showRatings": { "type": "boolean", "default": true }
  },
  "supports": { "html": false, "align": [ "wide" ] },
  "editorScript": "file:./index.js",
  "render": "file:./render.php"
}

Register it from the plugin with one line, pointing at the folder that holds block.json (the built folder when you use @wordpress/scripts):

PHP
<?php
add_action( 'init', function () {
    register_block_type( __DIR__ . '/../blocks/reading-list' );
} );

render.php receives $attributes, $content and $block as variables. It combines the block's attributes with the site settings, queries the books and prints escaped HTML:

PHP
<?php
/**
 * Server-side render for acme/reading-list.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused).
 * @var WP_Block $block      Block instance.
 */

$settings = wp_parse_args( get_option( 'acme_reading_settings', [] ), [ 'default_count' => 5, 'show_ratings' => 1 ] );

$count  = isset( $attributes['count'] ) ? max( 1, (int) $attributes['count'] ) : (int) $settings['default_count'];
$status = $attributes['status'] ?? 'all';

$args = [
    'post_type'      => 'acme_book',
    'posts_per_page' => $count,
    'no_found_rows'  => true,
    'orderby'        => 'title',
    'order'          => 'ASC',
];
if ( 'all' !== $status && in_array( $status, acme_reading_statuses(), true ) ) {
    $args['meta_query'] = [ [ 'key' => 'acme_status', 'value' => $status ] ];
}

$books = get_posts( $args );
?>
<div <?php echo get_block_wrapper_attributes(); ?>>
    <?php if ( ! $books ) : ?>
        <p><?php esc_html_e( 'No books yet.', 'acme-reading' ); ?></p>
    <?php else : ?>
        <ul>
            <?php foreach ( $books as $book ) : ?>
                <li>
                    <strong><?php echo esc_html( get_the_title( $book ) ); ?></strong>
                    <?php echo esc_html( get_post_meta( $book->ID, 'acme_author', true ) ); ?>
                    <?php if ( ! empty( $attributes['showRatings'] ) ) : ?>
                        <span aria-label="<?php echo esc_attr( sprintf( __( 'Rating: %d of 5', 'acme-reading' ), (int) get_post_meta( $book->ID, 'acme_rating', true ) ) ); ?>">
                            <?php echo esc_html( str_repeat( '*', (int) get_post_meta( $book->ID, 'acme_rating', true ) ) ); ?>
                        </span>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
</div>

get_block_wrapper_attributes() outputs the wrapper's class and the user's chosen alignment, colors and spacing, so theme and editor styling just work. The editor script is small. It describes the sidebar controls and previews the block by asking the server to render it:

JavaScript
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl, RangeControl, ToggleControl } from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import metadata from './block.json';

registerBlockType( metadata.name, {
  edit( { attributes, setAttributes } ) {
    return (
      <div { ...useBlockProps() }>
        <InspectorControls>
          <PanelBody title="Reading list">
            <SelectControl
              label="Status"
              value={ attributes.status }
              options={ [ 'all', 'to-read', 'reading', 'finished' ].map( ( v ) => ( { label: v, value: v } ) ) }
              onChange={ ( status ) => setAttributes( { status } ) }
            />
            <RangeControl label="How many" min={ 1 } max={ 20 } value={ attributes.count }
              onChange={ ( count ) => setAttributes( { count } ) } />
            <ToggleControl label="Show ratings" checked={ attributes.showRatings }
              onChange={ ( showRatings ) => setAttributes( { showRatings } ) } />
          </PanelBody>
        </InspectorControls>
        <ServerSideRender block={ metadata.name } attributes={ attributes } />
      </div>
    );
  },
  save: () => null, // Dynamic block: PHP renders the output.
} );

save: () => null is the signature of a dynamic block. Because nothing is saved, you can change the PHP later and every existing post updates at once.

Step 4: a settings page

Defaults belong in one option: an array stored under acme_reading_settings. The Settings API handles the form, the nonce, the saving and the sanitizing (see the Settings API).

PHP
<?php
add_action( 'admin_init', function () {
    register_setting( 'acme_reading', 'acme_reading_settings', [
        'type'              => 'array',
        'sanitize_callback' => 'acme_sanitize_reading_settings',
        'default'           => [ 'default_count' => 5, 'show_ratings' => 1 ],
    ] );

    add_settings_section( 'acme_reading_main', __( 'Display', 'acme-reading' ), '__return_false', 'acme-reading' );

    add_settings_field( 'default_count', __( 'Books to show', 'acme-reading' ), function () {
        $o = get_option( 'acme_reading_settings', [] );
        printf( '<input type="number" min="1" max="20" name="acme_reading_settings[default_count]" value="%d">',
            esc_attr( $o['default_count'] ?? 5 ) );
    }, 'acme-reading', 'acme_reading_main' );

    add_settings_field( 'show_ratings', __( 'Show ratings', 'acme-reading' ), function () {
        $o = get_option( 'acme_reading_settings', [] );
        printf( '<input type="checkbox" name="acme_reading_settings[show_ratings]" value="1" %s>',
            checked( ! empty( $o['show_ratings'] ), true, false ) );
    }, 'acme-reading', 'acme_reading_main' );
} );

function acme_sanitize_reading_settings( $input ): array {
    $input = is_array( $input ) ? $input : [];
    return [
        'default_count' => max( 1, min( 20, absint( $input['default_count'] ?? 5 ) ) ),
        'show_ratings'  => empty( $input['show_ratings'] ) ? 0 : 1,
    ];
}

add_action( 'admin_menu', function () {
    add_options_page( __( 'Reading List', 'acme-reading' ), __( 'Reading List', 'acme-reading' ),
        'manage_options', 'acme-reading', function () {
            if ( ! current_user_can( 'manage_options' ) ) {
                return;
            }
            echo '<div class="wrap"><h1>' . esc_html( get_admin_page_title() ) . '</h1><form method="post" action="options.php">';
            settings_fields( 'acme_reading' );
            do_settings_sections( 'acme-reading' );
            submit_button();
            echo '</form></div>';
        } );
} );

Unchecked checkboxes send nothing, which is why the sanitizer treats a missing show_ratings as 0. Keep related settings in a single array option so you make one database read, and mind that it is loaded on every request when autoloaded (see the Options API).

The block render and settings, runnable

This stand-in covers the sanitizer and the render function: defaults from settings, attribute overrides, filtering by status, ratings and escaping.

PHP Dynamic block render and settings sanitizer (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 how R&D <Notes> is displayed as text, and how a count of 500 is clamped to 20. Because the block is dynamic, changing the setting or adding a book changes every page that contains the block immediately.

Ideas to extend it

  • Add a "Finished on" date field and sort finished books by it (see meta queries).
  • Add a genre taxonomy and a block attribute to filter by it.
  • Cache the REST list in a transient, invalidated when a book is saved.
  • Add uninstall cleanup for the books and the option.
  • Replace the star characters with a styled rating component.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does save returning null in the editor script tell you about the block?

    A dynamic block stores only its attributes in the post. The front-end HTML is produced by the render callback or render.php.
  2. 2. In a REST route, what order do the checks run in?

    WordPress checks permissions and validates arguments before your callback runs, so the callback can assume clean input.
  3. 3. Why does the settings sanitizer set show_ratings to 0 when the key is missing?

    An unchecked checkbox is simply absent from the submitted form, so the sanitizer must treat absence as off.
  4. 4. Why is the update-status route protected with current_user_can( 'edit_post', $id ) rather than just being logged in?

    Being logged in says nothing about what you may change. Capability checks tie the action to the user's rights over the specific post.

Summary

  • Register the post type and its meta with types, defaults, sanitize callbacks and show_in_rest.
  • A custom REST route needs a permission_callback; args with enum, minimum and maximum validate input before your callback.
  • A dynamic block has a block.json, a render.php, and save: () => null; use get_block_wrapper_attributes() and escape all output.
  • The Settings API stores defaults in one array option and sanitizes it on save; unchecked boxes arrive as missing keys.
  • The block, the REST route and the settings share one source of truth: the books and one option.
  • The runnable code is a plain-PHP stand-in, not real WordPress.

Next: WordPress Exercises with Solutions