Contact!

Adding fields to the WordPress REST API

The WordPress REST API is an incredibly powerful tool; it allows us to use the CMS in exciting ways. In particular it allows us to use reactive frameworks for our front-end development. For example, we could use WordPress as a back-end (headless) and a reactive framework like Vue.js or React as our front-end. We could also create an app which uses data stored in WordPress on our mobile devices or even access data using calls in our custom plugins.

Extending the WordPress API

Out of the box the API gives us access to several useful fields (https://[yourdomain.com]/wp-json/wp/v2/posts). I expect that you’ll want to extend these, though. For example, we don’t have access to the post author name or feature image url by default. Let’s have a look at extending the the API to include these.

Register a rest field

To register new rest fields we use the register_rest_field() function. This field takes 3 arguments.

The first argument can be a string or an array. It allows us to define the content types we would like to register the field to. In this example we will registering from a ‘post’.

The second argument gives the field a name. This should just be a string.

The third argument is an array of arguments that we can use to populate the field we are registering. In this example we are going to use a ‘callback’ function to pass specific values to our new field.

register_rest_field(array('post'), 'gb_author_name', array('get_callback' => 'gb_get_author_name'));

register_rest_field(array('post'), 'gb_feature_image', array('get_callback' => 'gb_get_featured_image'));

Passing the author name

We are going to use a ‘callback’ function to pass the author name into our new rest field. We start by declaring our function.

function gb_get_author_name($object, $field_name, $request) {

}

Then we want to check when we are dealing with the author object and return the display name using get_the_author_meta().

function gb_get_author_name($object, $field_name, $request) {
    if ($object['author']) {
        return get_the_author_meta('display_name', $object['author']);
    } else {
        return;
    }
}

Passing the featured image url and alt text

Next we will look at how to use a ‘callback’ function to pass an array consisting of the featured image url and alt text.

Again we start by declaring our ‘callback’ function.

function gb_get_featured_image($object, $field_name, $request) {

}

This time we want to check whether the object is the featured media. We can now grab the image url using wp_get_attachment_image_src() and the alt text with get_post_meta() and return an array of the results.

function gb_get_featured_image($object, $field_name, $request) {
    if ($object['featured_media']) {
        // Get the image url and the post meta from the featured media ID
        $image = wp_get_attachment_image_src($object['featured_media'], 'full');
        $alt = get_post_meta($object['featured_media'], '_wp_attachment_image_alt', true);

        return array('url' => $image[0], 'alt' => $alt);
    } else {
        return;
    }
}

Advanced Custom Fields

I frequently use the Advanced Custom Fields pro (ACF) plugin. I find this useful because it allows me to make flexible fields quickly. Luckily there is a handy plugin to expose any ACF fields to the rest API. You can download it here.

  1. Muhammad Bilal says:

    🙁

  2. Greggbes says:

    Полезно

  3. Sam says:

    I had to look for hours until I stumbled across your explanation! This is easy to understand and so modifying to code to my liking was a piece of cake! Saved me a lot of headaches!

    Didn’t know about the plugin either so thank you so much!

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!