What you need to know about the new WordPress REST API

By Kirsty Burgoine

WordPress 4.4 made the WordPress REST API a part of the core.

In this article I’ll explain why this development is huge for WordPress (and theme and plugin authors in general) and show you how to use it to simplify the process of communication between WordPress and other apps.

The WordPress Rest API also makes it possible for WordPress websites to get rid of the default WordPress admin interface to offer a completely personalized admin or content experiences using a diverse technology stack.

Calypso – WordPress’ desktop app – is a beautiful example of this. Calypso is built using a single Javascript application that uses the WordPress REST API to communicate between WordPress.com and the core.

Because the WordPress REST API is now an integral part of WordPress core, it is important the developers get a good handle on how it works and the new possibilities it opens up for interacting with WordPress.

And so in this WordPress REST API overview and tutorial, I’ll walk you through the basics of the WP REST API as well as show you how you can use it to create a (plugin) widget that displays the latest posts from the Heroic Knowledge Base custom post types.

A primer on the WordPress REST API

Before we see how to use the WordPress REST API to create a (plugin) widget, let’s first understand the term a little better.

So what does API stand for?

API stands for Application Program Interface.

In simplest terms, it’s a means of communication between two different applications.

A common example of an API in action is the Tweet Deck that a lot of websites display. Displaying this Tweet Deck becomes possible via an API where the website just pulls data from Twitter and displays it.

What about REST?

REST is short for REpresentational State Transfer.

REST is an HTML-based architectural style of building APIs. A RESTful architecture uses HTTP requests to post, read, update, and delete data between two sources.

So when we talk of a REST API, we essentially mean an API that uses HTML methods to communicate.

And what about JSON?

The WordPress REST API is the same format as the WordPress JSON REST API.

JSON (or Javascript Object Notation) is a minimal, text based data-interchange format that’s used to seamlessly exchange data between different platforms (even if the platforms use different languages).

JSON is a lightweight alternative to XML-based solutions, making it perfect for mobile apps with bandwidth limitations.

Why use the WordPress REST API

You might be wondering about what’s so exceptional about the WordPress REST API and why you should care about it.

Well … the WordPress REST API empowers you to do more with WordPress.

For example:

  1. Write applications in any language you know and make it interact with a WordPress site (the only 2 requirements being that your app’s language should use HTML methods and be able to interpret JSON)
  2. Design completely personalized admin and content experiences
  3. Develop Single Page Applications on top of WordPress

And much more.

It’s almost impossible to list down all the potential applications/interfaces/experiences that can be created with the REST API. WordPress’ REST API handbook rightly says:

Our imagination is the only limit to what can be done with the WordPress REST API. The bottom line is, if you want an structured, extensible, and simple way to get data in and out of WordPress over HTTP, you probably want to use the REST API.

But I know implementation is always much more difficult than understanding theory.

So let’s see a quick tutorial on how you can use the WordPress REST API to create a custom (plugin) widget.

A quick tutorial on how to use the WordPress REST API

If you have one of our knowledge base products, such as our KnowAll help center theme or the your own theme with the Heroic Knowledge Base plugin, you’ll have a site with a knowledge base of support articles. Using these products isn’t necessary to follow the principles of this tutorial, however, just be mindful you’ll need to tailor any code to your own setup.

So, ready with your local setup?

Great!

Now what we’re going to do is create another website on a different server.

So why are we creating this second website?

We’re doing so because we want to implement the WordPress REST API to communicate with this second website, and as you now know, the WordPress REST API is all about making conversations happen.

So we’re going to use the WordPress REST API to get the two websites to talk to each other and exchange data.

And the end goal of the tutorial is to:

Pick the latest published knowledge base articles from the help center website and display them in a widget in the sidebar of the new website.

For the sake of this article, the help center website that has all the knowledge base articles will be referred to as the ‘local’ website and the new website where you will be displaying the widget will be the ‘external’ website.

At this point, I’m assuming that you have 1) your ‘local’ help center website, and 2) a new ‘external’ website set up on a different server.

And at the end of the tutorial, we would have successfully displayed a list of knowledge base articles from the ‘local’ website on the new ‘external’ website (via the WordPress REST API) using a custom (plugin) widget.

With that, we’re ready to begin:

Step#1: Start by copying the following boilerplate code into a new .php file and save it in the plugins folder of your ‘external’ website.

See the complete code for this WordPress REST API tutorial here.

/**
* HeroThemes Example Widget
*/
class My_Widget extends WP_Widget { 

    //set up widget
    public function __construct() { 

        $widget_ops = array( 
                        'classname' => 'rest-api-test-widget',
                        'description' => 'This example provides a framework for how we will build our widget'
        );

        parent::__construct( 'my_widget', 'My Widget', $widget_ops );
    }


    /**
     * Outputs the content of the widget
     * @param array $args
     * @param array $instance
     */

    public function widget( $args, $instance ) {
        //outputs the content of the widget
        echo $args['before_widget'];

        if( !empty( $instance['title'] ) ) {
          echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];

        }

        // Main Widget Content Goes Here

        echo $args['after_widget'];
    }


    /**
     * Outputs the options form on admin
     * @param array $instance The widget options
     */

    public function form( $instance ) {
        //outputs the options form on admin
        $title = ( !empty( $instance['title'] ) ) ? $instance['title'] : ''; ?>

        <label for="<?php echo $this->get_field_name( 'title' ); ?>">Title: </label>

        <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" 
        name="<?php echo $this->get_field_name( 'title' ); ?>" 
        type="text" value="<?php echo esc_attr( $title ); ?>" />
    
        <?php 
    } 

} 

 add_action( 'widgets_init', function(){ register_widget( 'My_Widget' ); } ); 

 

This code creates a very simple widget that will display a title of your choosing.

By adding the code at the top of the template and saving it to the plugins directory, we have created it as a plugin (rather than adding the code to the theme’s functions file).

Its a small thing but creating a widget as a plugin in this style allows you to be able to switch it on and off and also re-use it in other themes later if you wish, without the need to copy and paste.

Once installed and activated, you will have a new widget in the Widgets area of the dashboard:

widget-admin

Step #2: Use the WordPress REST API to fetch the recent knowledge base articles

Because you don’t want to edit or delete anything in this development, we are only going to focus on the widget() function. This is where the content from the widget is outputted to the ‘external’ website.

In order to ‘get’ the list of the recent knowledge base articles from the ‘local’ website, there are a few things we need to know:

  • The base path of the API (what API to use on your site, in our case the latest WP API)
  • The route used  (WP API has multiple routes for the different data sets and operations available)
  • The endpoint used (What action is to be performed)
  • Parameters (The data associated with the request)

The base path of the API is always:

 json/wp/v2/ 

And so the absolute API path becomes:

 http://example.com/json/wp/v2/ 

(http://example.com is your ‘local’ website)

The route used is:

 json/wp/v2/posts/ 

About the endpoints: This route actually has three endpoints that are differentiated by the HTTP methods. These endpoints are:

  • GET
  • PUT
  • DELETE

In this example, you’ll choose the GET endpoint so that you can retrieve (or ‘get’) a list of latest posts from the ‘local’ website.

So your first line of code interacting with the REST API will be:

$response = wp_remote_get( 'http://products-website.com/wp-json/wp/v2/posts/' );

Next, you need to check if any errors are returned:

if( is_wp_error( $response ) ) {
    return;
}

All this code does is check what response is returned. If the response returns some posts, then there’s no error.

The last part of this section is:


$posts = json_decode( wp_remote_retrieve_body( $response ) );

if( empty( $posts ) ) {
   return;
}

$response is a JSON encoded string with Post data. So all you’re doing here is decoding it so that it can be outputted.

Again, add an additional check to ensure $posts is not empty. If it is, then nothing is returned.

So, at this point, you have successfully communicated with your ‘local’ website using the API. This implementation leaves you with a list of posts to display.

The next stage is to actually display them in your widget on the ‘external’ website.

Step #3: Display the latest posts on the ‘external’ website by adding the following code:

		if( !empty( $posts ) ) {
		
			echo '<ul>';
			foreach( $posts as $post ) {
				echo '<li><a href="' . $post->link. '">' . $post->title->rendered . '</a></li>';
			}
			echo '</ul>';
			
		}

The code for your completed widget should look like this:

/**
* HeroThemes REST API Widget
*/
class REST_API_Widget extends WP_Widget { 

	//set up widget 
	public function __construct() { 
		$widget_ops = array( 	'classname' => 'rest-api-widget',
 								'description' => 'A REST API widget that pulls posts from a different website'
 		);
 		parent::__construct( 'rest_api_widget', 'REST API Widget', $widget_ops );
 	}

	/**
	* Outputs the content of the widget
	*
	* @param array $args
	* @param array $instance
	*/
	public function widget( $args, $instance ) {
		//change this url to the WP-API endpoint for your site!
		$response = wp_remote_get( 'https://example.com/wp-json/wp/v2/ht-kb/' );

		if( is_wp_error( $response ) ) {
			return;
		}

		$posts = json_decode( wp_remote_retrieve_body( $response ) );

		if( empty( $posts ) ) {
			return;
		}

		echo $args['before_widget'];
		if( !empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];
		}
		
		//main widget content
		if( !empty( $posts ) ) {
		
			echo '<ul>';
			foreach( $posts as $post ) {
				echo '<li><a href="' . $post->link. '">' . $post->title->rendered . '</a></li>';
			}
			echo '</ul>';
			
		}

		echo $args['after_widget'];
	}

	/**
	* Outputs the options form on admin
	*
	* @param array $instance The widget options
	*/
	public function form( $instance ) {
		// outputs the options form on admin
		$title = ( !empty( $instance['title'] ) ) ? $instance['title'] : '';
		?>

		<label for="<?php echo $this->get_field_name( 'title' ); ?>">Title: </label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" 
		  name="<?php echo $this->get_field_name( 'title' ); ?>" 
		  type="text" value="<?php echo esc_attr( $title ); ?>" />
		
		<?php 
	} 

 } 

 add_action( 'widgets_init', function(){ register_widget( 'REST_API_Widget' ); } ); 

With the above step done, when you now try viewing your ‘external’ website, you’ll see a list of your posts from the ‘local’ website in your sidebar.

widget

This is all great.

However, if you remember, these are not the right posts because we only want to show the latest articles from the Knowledge Base.

Our current implementation doesn’t do this because the Knowledge Base plugin uses its own custom post type. And because custom post types are not publicly available to APIs by default, this causes a problem. (Note: The latest version of the knowledge base is publicly available to the REST API and the next section can be skipped)

Using the REST API with custom post types

To make custom post types available to the REST API, you need a little workaround.

So, when creating a custom post type, you need to add a new parameter to the register the post type args to make it publicly available:


'show_in_rest' = true,
'rest_base' = 'ht_kb',
'rest_controller_class' = 'WP_REST_Posts_Controller',

But because in our case, we’re using a plugin for powering the knowledge base article post type, we won’t directly edit the plugin file to make the custom post types available to the REST API. (Editing a plugin file directly is never a good idea!)

What we’ll do instead is add the following code to the functions.php file in the child theme for the ‘local’ website:

The latest version of KnowAll and Heroic Knowledge Base already have REST support enabled, this can be disabled with the ht_kb_show_in_rest filter, but you can modify the code below for your own custom post type.
/**
* Add rest support to an existing post type
*/
add_action( 'init', 'my_custom_post_type_rest_support', 25 );

function my_custom_post_type_rest_support() {
    global $wp_post_types;

    //set this to the name of your post type!
    $post_type_name = 'ht_kb';
    if( isset( $wp_post_types[ $post_type_name ] ) ) {
        $wp_post_types[$post_type_name]->show_in_rest = true;
        $wp_post_types[$post_type_name]->rest_base = $post_type_name;
        $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
    }
}

Now, the custom post type ‘ht_kb’ is publicly available to the WP REST API.

After making the custom post type available to the WordPress REST API, we now need to fix our widget to show posts with that post type. For that, we’ll go back to the $response code from Step #2 and update it to:

$response = wp_remote_get( 'http://example.com/wp-json/wp/v2/ht_kb/' );

We’re basically changing the /posts/ to /ht_kb/ in the API route because ‘ht_kb’ is the name of the plugin’s custom post type.

Once you update your widget and preview the ‘external’ website, you should now see the latest articles from the Knowledge Base.

widget-kb-content

Final thoughts

Well as we have seen, using a few simple snippters of PHP and HTML, you can create new functions, widgets, and plugins.

You could amend the plugin we just made to create a search box that uses the WP REST API to search the Knowledge Base articles and return the results in the widget.

Or, you could use authentication to control who sees the results (useful if you have created restricted content).

There’s so much you can try! Just get the basics right, and you’ll be all set.

Further reading

There’s a lot of obsolete content around the WordPress REST API, so make sure you just read the updated stuff. I’ve linked to some useful resources all through the post, but I’m listing some here as well.

So read up on them and find out the different creative ways that you can use the REST API.

If you’ve any questions about implementing the WordPress REST API, drop them in the comments below!

Leave A Comment?