Unlimited Wordpress themes, plugins, graphics & courses! Unlimited asset downloads! From $16.50/m
Advertisement
  1. Web Design
  2. REST API

How to Use the WordPress REST API: A Practical Tutorial

by
Difficulty:IntermediateLength:LongLanguages:

The WordPress REST API was first introduced with version 4.7 and brought fantastic opportunities and functionality to WordPress development. The WordPress REST API allows developers to interact with WordPress sites remotely by sending and receiving JSON (JavaScript Object Notation) objects. 

This means now you can build websites, mobile apps, desktop apps, all based on WordPress from the back-end, but “without” WordPress on the front-end.

Our WordPress REST API Example

In this practical WordPress REST API tutorial I’ll explain how you can use the REST API to create a multi-layout portfolio with an AJAX filter. This example will explain how to work with the REST API, how to extend it, and why using the WordPress REST API with AJAX will take your development skills to the next level!

Here is the demo site we’ll build.

The Steps We’ll Take

  1. Create custom post type “tutorials”
  2. An Introduction to the WordPress REST API with Postman
  3. How to extend the WordPress REST API
  4. Create a Tutorials Shortcode with an AJAX Powered Filter and the WordPress REST API
  5. Conclusion and Next Steps

Note: this tutorial assumes some understanding of WordPress development, and JavaScript.

Wait, What’s a REST API?

One popular way to describe an API is with the shop assistant metaphor. As a customer, you make a request to the shop assistant (the API) who then dutifully heads out to the storeroom and fetches back what you asked for, based on the details you provided. 

REST APIs are the preferred form of API for internet use because although they are perhaps less robust than the alternatives, they are relatively simple and flexible thanks to their use of fewer rules/guidelines.

REST APIs deal purely with these four HTTP requests:

  • GET
  • PUT
  • POST
  • DELETE

1. Create Custom Post Type “Tutorials”

Since WordPress version 2.9 (almost ten years ago!) it’s been possible to create custom post types, allowing developers to extend WordPress beyond posts and pages. This is all thanks to the introduction of register_post_type().

I won’t cover in detail how to create custom post types here, as this is purely a WordPress REST API tutorial, but the Tuts+ tutorial series A Guide to WordPress Custom Post Types will help you get started.

The WordPress REST API works with default “post” and “page” post types as well as custom post types. However, with custom post types you need to extend the REST API.

Create a WordPress Plugin for Our Code

For the purposes of this tutorial all our code will be placed inside a simple WordPress plugin (plugin creation won’t be described in detail for the same reason as above). 

At this moment you should have a fresh WordPress install with the default theme active. Create a simple WordPress plugin called “tutorials” and put the following code in it:

By default no post types have REST API support, so we will need to tell WordPress to enable it. We do so in the register_post_type() function, so add the following (large snippet) after the plugin intro data:

Tip: for an easy way to generate all this for you, use the tools provided by generatewp.com, or a plugin like Custom Post Type UI

Here we’ve created the “tutorial” custom post type with two taxonomies “tutorial-category” and “tutorial-tag”. Take a closer look at these two parameters within the $args array:

  • 'rest_controller_class' => 'WP_REST_Posts_Controller',
  • 'rest_base'             => 'tutorial',

With these we tell WordPress to enable REST API support for the custom post type “tutorial”. We use two similar parameters for our two taxonomies:

  • 'rest_controller_class' => 'WP_REST_Terms_Controller',
  • 'rest_base'             => 'tutorial_category',
  • 'rest_controller_class' => 'WP_REST_Terms_Controller',
  • 'rest_base'             => 'tutorial_tag',

Note: your custom post and taxonomy slugs can include a dash, but for the rest_base parameter it is highly recommended to use an underscore, as all REST API parameters use underscores.

There we go! Now once you activate the plugin WordPress will enable REST API support for our custom post type and custom taxonomies. Head to the WordPress dashboard and reload the page. You will see the Tutorials custom post type appear in the WordPress menu. Now go to Settings > Permalinks and set the following permalinks structure /%category%/%postname%/. With the WordPress REST API it is much easier to work with a custom permalinks structure.

tutorials custom post type
Our “Tutorials” custom post type

Add Some Sample Data

Let’s add some sample tutorials to work with. I’ve added some tutorial content from Tuts+ so the tutorials archive page now looks like this. 

tutorials archive page

As we don’t have a specified archive page for tutorials, WordPress takes the default post archive page layout and structure to display the tutorials. At this point we are ready to switch to REST API.

2. An Introduction to the WordPress REST API with Postman

Postman is a very powerful tool to connect, test, and work with any API–download and install it to your system. To start working with the WordPress REST API we’ll need to refer to the detailed documentation. Here we have all the information needed to work with the REST API. For now, open Postman and send a new GET request with the following url (our endpoint) http://yoursite.com/wp-json/wp/v2/tutorial. You should get the similar results.

Postman

Where did we get this endpoint URL specifically? From the documentation:

“If we make a GET request to http://yoursite.com/wp-json/, we will get a JSON response showing us what routes are available, and within each route, what endpoints are available. ”

Our endpoint fetches data from our tutorial custom post type. 

In WordPress I added six tutorials and postman shows them all, until I restrict the tutorials number with the per_page parameter, like this: http://yoursite.com/wp-json/wp/v2/tutorial?per_page=1. Now we get only one tutorial. And if you want to add more parameters use the & symbol, like this: http://yoursite.com/wp-json/wp/v2/tutorial?per_page=1&status=publish

Examine the returned data. We’re given lots of very useful information, like the tutorial id, tutorial-category ID, title, excerpt, and tutorial link–everything we need for our AJAX function. 

However, you might have noticed that although we have the tutorial category/tag IDs, and attachment IDs, we don’t have their links. In a PHP environment it’ no problem to get the term/attachment link from the term ID as WordPress has built-in functions for doing so: get_term_link() and wp_get_attachment_image_src(). But in JavaScript we don’t have that luxury, so we will need to extend the REST API to return the term links and the post image’s absolute URL.

3. How to Extend the WordPress REST API

Happily, extending the WordPress REST API is as simple as adding a custom field. Say hello to register_rest_field(). Open the plugin file we’ve been working on and at the very bottom, after all the content so far, add the following code:

The first parameter of register_rest_field is post type. Next we give the name of the new rest field tutorial_category_attr and tutorial_tag_attr. The rest are optional function arguments:

  • get_callback The callback function used to retrieve the field value. Default is 'null', the field will not be returned in the response.
  • update_callback The callback function used to set and update the field value. Default is 'null', the value cannot be set or updated.
  • schema The callback function used to create the schema for this field. Default is 'null', no schema entry will be returned.

Now let’s create the callback functions for both rest fields.

Each callback function requires three parameters (one is required, the other two are optional): $object, $fieldname and $request. Here we create an associative array of term name and term link for each tutorial category and each tutorial tag.

For now, if you go back to Postman and again request the API results with GET, you will see new REST API fields added.

new REST API fields

Now we are really ready to do some AJAX.

4. Create a Tutorials Shortcode with an AJAX Powered Filter and the WordPress REST API

For this step we’ll create a simple shortcode with recent tutorials and an AJAX category filter. Our shortcode will have layout options, like list and grid. We’ll start with the add_shortcode() function, so add the following code at the very bottom of the plugin file:

Again, as this is fundamentally a WordPress REST API tutorial, I won’t explain how to create shortcodes here, but I will explain what this shortcode does: it returns recent tutorials with a different structure to the one we have in the archive page, and builds a category filter created with the get_terms() function.

The shortcode output looks like this:

It needs some styling! Before the shortcode function add this code, in order to enqueue a stylesheet in which we’ll write our styles:

Then, in our plugin folder, create a file: “css/tuts.css”, and add some basic styling:

Now both the list and grid layouts look much better!

list layout
grid layout

AJAX Filter Functionality

It is time to create the AJAX and REST API filter functionality. Let’s create and enqueue our script file. In the envato_styles_scripts() function, after the stylesheet, add the following code

We will register the script and enqueue with the shortcode output. In the shortcode function file, right after the if($tuts->have_posts()){ add the following code:

As before with the stylesheet, you’ll need to have the js folder with the tuts.js file in it. Before writing any code in the tuts.js file we need to localize some parameters with this file with the wp_localize_script() function. Add the following code after the wp_register_script():

This is a REST API endpoint for tutorials, and is required for our AJAX function. Add the following jQuery code in the tuts.js file:

Our code consists of eleven steps, and I will explain each one:

  1. Create all the required variables. This step is self-explanatory; here we create our required variables.
  2. Term filter click event. This sets the click event on each term link in the filter.
  3. As links have the href attribute, we need to prevent the link default behavior so as not to leave the page. After that we need to be sure that no other filter request is running at the moment. If no request is running we set a new one.
  4. Remove current items from the tuts list to free the space for newcomers.
  5. Get current clicked filter href, id and toggle the active class.
  6. Build the final AJAX url that we will send request to. This is simple function output that takes the REST API formatted link and ads the per_page attribute if one is specified with the shortcode settings.
  7. Send the AJAX request with JSON data type and the JSON URL we built.
  8. If the request is successful we loop through each response object. Remember the postman output of our example API requests? Each post item we get is a response object. Here is the key difference between a simple AJAX get request and an AJAX JSON REST API request: we don’t get the structured HTML data, we get an OBJECT, that contains information and now we are free to use this object data with any layout we want.
  9. If output is ready append new tuts into the tuts list with jQuery append.
  10. If something goes wrong we need to tell the user that the request failed.
  11. And always, whether we were successful or failed, we need to stop the current AJAX request.

Conclusion

Well done! You’ve used JavaScript (with jQuery) to pull data from our WordPress backend. We used the WordPress REST API and extended it in order to access our custom post type. 

Next Steps

Now that you know how to work with the WordPress REST API, you can take it even further and pull WordPress data from outside the WordPress environment. Here’s an example HTML site with the latest tutorials from our WordPress website without WordPress.

This is a rudimentary page, but demonstrates how you can use WordPress data outside of WordPress. It can be a mobile app, or a desktop app, or (my favorite situation) a progressive web app for all platforms and operating systems, built with WordPress as the CMS and a web app for the front-end.

Feel free to pull the code from the GitHub repo and play around! If you have any questions or thoughts on what we’ve built here, please leave them in the comments section.

More WordPress REST API Tutorials and Courses

Advertisement
Advertisement
Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.