Using the WordPress REST API as a Headless CMS Backend

Use the WordPress REST API as a headless CMS backend

In a headless setup WordPress is only the place where content is written and stored. The site that visitors see is a separate application, for example in React or Vue, that reads the content through the REST API. Editors keep the familiar admin, and the front end can be built with any technology.

Problem: The front end is a JavaScript application, but the content should still be managed in WordPress.

Solution: Read posts, pages, terms and media from the REST API at /wp-json/wp/v2/, make custom post types available with show_in_rest, and add your own fields to the responses with register_rest_field().

The endpoints

# Published posts, 10 per page
GET /wp-json/wp/v2/posts?per_page=10&page=1

# One post by ID, or by slug
GET /wp-json/wp/v2/posts/42
GET /wp-json/wp/v2/posts?slug=my-article

# Posts of a category (term ID 5)
GET /wp-json/wp/v2/posts?categories=5

# Embed linked objects (featured image, author, terms) into the answer
GET /wp-json/wp/v2/posts?_embed

# Only some fields
GET /wp-json/wp/v2/posts?_fields=id,slug,title,excerpt,date

# Categories
GET /wp-json/wp/v2/categories

A custom post type appears at /wp-json/wp/v2/{rest_base} only if it is registered with 'show_in_rest' => true.

Reading posts in JavaScript

The number of posts and pages comes in the response headers, not in the body:

function getPosts( page ) {
    var url = 'https://example.com/wp-json/wp/v2/posts?per_page=10&_embed&page=' + page;

    return fetch( url ).then( function ( response ) {
        var totalPages = parseInt( response.headers.get( 'X-WP-TotalPages' ), 10 );

        return response.json().then( function ( posts ) {
            return { posts: posts, totalPages: totalPages };
        } );
    } );
}

getPosts( 1 ).then( function ( result ) {
    result.posts.forEach( function ( post ) {
        var media = post._embedded && post._embedded[ 'wp:featuredmedia' ];
        var image = media && media[ 0 ] ? media[ 0 ].source_url : '';
        console.log( post.title.rendered, image );
    } );
} );

The featured image is not in the post itself, only its ID (featured_media). _embed includes the image object, so you do not need a second request per post.

Adding a field

A reading time for every post, calculated on the server:

<?php
add_action( 'rest_api_init', function () {
    register_rest_field( 'post', 'reading_time', array(
        'get_callback' => function ( $post ) {
            $content = get_post_field( 'post_content', $post['id'] );
            $words   = str_word_count( wp_strip_all_tags( $content ) );

            return max( 1, (int) round( $words / 200 ) ); // minutes, 200 words per minute
        },
        'schema' => array(
            'description' => 'Estimated reading time in minutes.',
            'type'        => 'integer',
        ),
    ) );
} );

What headless costs

WordPress no longer renders the pages, so everything the theme did must be done again in the front end: URLs and redirects, previews of drafts, SEO tags, sitemaps, forms, comments. Plugins that change the front end (SEO, caching, page builders) have no effect. For a blog this is a lot of work; it pays off when the content is shown in several places, for example on a site and in a mobile app.

NOTE: Use _fields in list views. A full post object with the rendered content can be tens of kilobytes; a list of titles and excerpts needs only a fraction of that.