Back to blog

Using the WordPress REST API

APIs have become more and more important in our projects lately. Therefore, it is difficult today to imagine a service, a project… that does not offer an API to interact with. In this article we will look at one type of API architecture in particular (and yes there are others) which is the REST and then the WordPress API and the exposure of custom fields/types of ACF.

What is an API?

An API (AApplication Programming IInterface) is, as its name indicates, an interface that allows communication between two programs. It allows the reception and transmission of data in different formats, specified by the developer in charge of the API design (JSON, XML, …).

The REST API

REST (Representational State Ttransfer) is a resource-oriented architecture where each resource is accessible via a unique identifier called URI.

Richardson’s maturity model

According to Richardson’s maturity model there are four 4 levels of development in REST APIs (from 0 to 3) of which level 3 represents a fully RESTful API.
The differentiation between the 4 levels can be based on 4 criteria:

verbes-http-api

HTTP verbs

REST uses HTTP verbs to define exchange specifications that can be easily integrated into any system.

http-verbs-summary-api-rest

WordPress API

Since version 4.7 of WordPress, a REST type API is integrated as standard without the need for a plugin and is totally designed with today’s standards.

rest-api-wordpress-endpoints

Creating custom post types

The creation of custom post types allows you to have a different type of content than the default WordPress content, i.e. articles, pages,…

Let’s imagine that we have to develop for a client a site that offers courses/formations, we have to create a custom post type course for which we would need to add custom fields; name of the course, type of the course… here is the piece of code to put in the functions.php file of our theme. The most important thing to check is that show_in_rest is at true since it allows us to retrieve this custom post from the API.

When it comes to taxonomies, WordPress defaults to categories and tags for posts. Again, we will need to have custom taxonomies for the type of post so that we can retrieve them later by category.

To retrieve all the courses a simple request GET is enough. But executing the request we receive a 404 code, which means that the resource is unavailable when everything is good. In this case we just have to re-register the permalinks by going to Settings > Permalinks.

Our custom post type formations is now created.

function custom_post_types()
{
    register_post_type(
        'formations',
        array(
          'labels' => array('name' => __('Formations'), 'singular_name' => __('Formation') ),
          'public' => true,
          'has_archive' => true,
          'public'       => true,
          'show_in_rest' => true,
          'supports' => array('title','editor','thumbnail','custom-fields'),
          'show_ui'             => true,
          'show_in_menu'        => true,
          'show_in_nav_menus'   => true,
          'show_in_admin_bar'   => true,
          'menu_icon'           => 'dashicons-welcome-learn-more',
        )
      );
    register_taxonomy(
        'category_formations',
        'formations',
        array(
          'label' => 'Categories',
          'labels' => array(
          'name' => 'Categories',
          'singular_name' => 'Category',
          'all_items' => 'All categories',
          'edit_item' => 'Edit category',
          'view_item' => 'View category',
          'public'       => true,
          'show_in_rest' => true,
          'show_ui' => false,
          'show_tagcloud' => false,
          'show_in_nav_menus' => false,
        ),
        'hierarchical' => true
        )
      );
}
add_action('init', 'custom_post_types');

Adding custom fields

ACF (Advanced Custom Fields) is a WordPress extension that allows you to add custom fields to posts (custom or default), called custom fields.

Previously we only created the custom post type formations to which we have to add fields. These fields will be the following: description, thumbnail, syllabus…

We assume that ACF (or ACF Pro) is already installed on our site. We start by creating a group of fields course Fields to which we will add all the necessary fields with their types.

acf-pro-wordpress

In order for this group of fields to be applicable to course type posts it must be assigned to it, as shown in the following capture:

acf-pro-type-wordpress

We can now create a course for the example with all the necessary fields.

formations-wordpress-acf

After creation we can now make a GET request to retrieve the course in question. To do this I will use Postman or Insomnia which are REST clients.

Here is the answer to the request:

response-api-acf-wordpress-formations

We have retrieved the content of all the post except the ACF fields. Basically ACF fields are not exposed in the REST API, it will be necessary to specify it also in the functions.php file of our theme.

add_action('rest_api_init', 'wp_rest_api_alter');
function wp_rest_api_alter()
{
    register_rest_field(
          'formations',
          'custom_fields',
          array(
            'get_callback'    => function ($data, $field, $request, $type) {
                if (function_exists('get_fields')) {
                    return get_fields($data['id']);
                }
                return [];
            },
            'update_callback' => null,
            'schema'          => null,
          )
      );
}

Benefits of using the WordPress REST API

  • Design of themes based only on JavaScript or a particular frontend framework (React.js, Vue.js, Angular,…)
  • Use of the API for single page applications
  • Using the API as a backend for mobile applications
  • Use of WordPress as Headless CMS (for Jamstack integration, more information on https://jamstatic.fr/)
  • Design of a dashboad entirely based for example on Node.js or other completely independent of the default WordPress dashboad.
  • etc…

We will see in the next articles how to use the WordPress API to create a blog based on GatsbyJS.

Before you leave…
Thanks for reading! 😊