Skip to Main Content

How to use the WordPress REST API

Divi: the easiest WordPress theme to use

Easily create your website with Elementor

Elementor allows you to easily create any website design with a professional look. Stop paying expensive for what you can do yourself. [Free]

Feature after feature, WordPress tends to drop the mantle of blogging system and into that of application development system. The first noticeable step towards this change was the introduction custom post types in its 2.9 version.

Today, the transformation continues with the arrival of WordPress REST API.

In this tutorial, I'll walk you through what the WordPress REST API is and show you how to use it.

But before, if you have never installed WordPress discover How to Install a WordPress Blog in 7 Steps et How to search, install and activate a WordPress theme on your blog 

Then let's go back to why we are here

What is the REST API

To put it simply, understand that the WordPress REST API allows you to interact with the core of WordPress without going through its graphical interface. This means a decoupling of the kernel and the GUI. With this API, you can for example create a new article, without having to access the dashboard. The REST API will be included in the kernel when version 4.4 is released by December.

Given the nature of the subject of this tutorial, a good knowledge of PHP language and WordPress is necessary.

What do we need for this tutorial

To get started with the REST API, you will need the plugin REST API as well as the latest version of WordPress. You have it ? If not, see whyKnowledge of the WordPress HTTP API will also be good companies for making remote calls.

Discover by clicking on this link How to install (add) a plugin on WordPress

As a project for this tutorial we will create a local installation of WordPress from which we will retrieve articles from our website through the REST API. Make sure you have the REST API plugin installed and activated on the production website.

Now, create a widget in your local installation. Here is the basic code:

/**
 * Plugin Name: REST API Widget Essai
 * Plugin URI: http://le-site-de-votre-widget-ici.com
 * Description: Ce widget récupère des articles à l'aide de l'API REST
 * Version: 1.0
 * Author: Votre nom
 * Author URI: http://votre-site.com
 */

class Mes_Articles_Widget extends WP_Widget {

    public function __construct() {
        $widget_details = array(
            'classname' => 'widget-essai-rest-api',
            'description' => 'Un widget qui récupère des articles à l'aide de l'API REST depuis un autre site'
        );

        parent::__construct( 'widget-essai-rest-api', 'REST API Widget Essai', $widget_details );

    }

    public function form( $instance ) {
        $title = ( !empty( $instance['title'] ) ) ? $instance['title'] : '';
        ?>

        <p>
            <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 ); ?>" />
        </p>

        <?php
    }
    public function widget( $args, $instance ) {
        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'];
        }
        // le code fonctionnel du widget ici
        echo $args['after_widget'];
    }
}
add_action( 'widgets_init', function(){
     register_widget( 'Mes_Articles_Widget' );
});

In the plugin directory of your local website, create a folder named widget-test-rest-api. In this folder, create a file named widget-test-rest-api.php and paste the code above.

Discover by the way How to manage and restore a version of WordPress with VersionPress

This code contains the plugin header (the comments at the start of the code) which lets WordPress know that it is an plugin. Next comes the minimum code for creating a widget, increased by a few lines. 

We will put more emphasis on function widget (), because it is inside this that the display of the widget is built. Therefore, it is inside this function that we will make the calls using the HTTP API.

Retrieve articles

We will need some information in order to query the production website or online website. These will in a way constitute the question posed to the WordPress core of our online website. These are the basic API path, the route used, the termination used, the headers, and the parameters.

Sublimate your illustrative images by discovering How to create interactive images on a WordPress blog

The basic WordPress REST API path is always / Wp-json / wp / v2 /. Thus, the full path will be http://votre-domaine.com/wp-json/wp/v2/.

The route used to retrieve the items is / posts. What makes the complete route for articles is http://votre-domaine.com/wp-json/wp/v2/posts.

Each route can have a number of terminations, differentiated by the HTTP method used. Thus the route of an article can be / Posts / 291. This road 3 endings:

Divi: The best WordPress theme of all time!

With over 901.000 downloads, Divi is the most popular WordPress theme in the world. It is complete, easy to use and comes with more than 62 free templates. [Recommended]

GET : to retrieve the article
PUT : to update the article
DELETE : to delete the article.

Using the HTTP API and the GET termination, retrieving the articles comes down to one line of code:

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

Make your articles popular by discovering How to add share buttons to WordPress

If the answer is an object WP_Error, we end the execution of our function widget ()if not, we examine the content of the body of the answer with the function wp_remote_retrieve_body looking for articles encoded in JSON format. This is what the function looks like widget ()  :

 public function widget( $args, $instance ) {
    $response = wp_remote_get( 'http://mysite.com/wp-json/wp/v2/posts/' );

    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'];
    }
    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'];
}

What is interesting in this example is that by replacing the function wp_remote_get otherwise, this example will be outside the scope of WordPress. This means that you can query the WordPress core from any other platform, be it Joomla, Prestashop, Drupal, Android or IOS.

Go further by discovering these 8 WordPress plugins to turn your website into a mobile application

You can therefore create a native mobile application connected to a WordPress back office. The REST API turns WordPress into an application development platform.

Go further with the REST API

Querying the WordPress core for the purpose of interacting with data constitutes 90% of its usage. But there are still a few areas that would be interesting to explore: cached response, authentication and service discovery.

Response caching

When we retrieve information such as the articles in our example, it is good practice to cache them, i.e. copy them somewhere on the calling terminal in order to avoid other calls for the same information to the server. Different approaches exist to achieve this including JP REST API CACHE, plugins cache, and transients.

The idea of ​​transient is to copy the information locally with an expiration date. By default, the copy will be in the database, but some implementations allow copying directly into memory, which makes the restore operation even faster.

See also these 7 premium WordPress plugins to optimize the caching of your website

The information is then retrieved from the local database until its expiration where, it is then recalled from the remote website. Here is a modified version of our widget which includes the notion of transient (with a new function):

public function get_remote_posts() {
    $posts = get_transient( 'remote_posts' );
    if( empty( $posts ) ) {
        $response = wp_remote_get( 'http://votre-domaine.com/wp-json/wp/v2/posts/' );
        if( is_wp_error( $response ) ) {
            return array();
        }

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

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

        set_transient( 'remote_posts', $posts, HOUR_IN_SECONDS );
    }

    return $posts;
}

public function widget( $args, $instance ) {
    $posts = $this->get_remote_posts();

    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'];
    }

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

    echo $args['after_widget'];

}

Authentication

When working with external resources, it is advisable to identify yourself. This is done through the authentication process. The REST API gives you two methods to identify yourself: Basic authentication and OAuth.

Basic authentication : of the two methods, this one is the simpler. It consists of sending your username and password with each request, which carries great security risks. For this reason, it should NOT be used in production as much as possible.

To use basic authentication, you must install and activate the plugin Basic-Auth. Then, to make an authenticated call, declare the header with Basic and make the call:

$headers = array (
    'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
);

$response = wp_remote_request( 'http://votre-domaine.com/wp-json/wp/v2/posts/1234/', array(
    'method' => 'DELETE',
    'headers' => $headers
));

See also how to add dual factor authentication on WordPress

Be careful with this example, because if you try it on your website, you will delete the article that has the ID 1234 if it exists..

OAuth : This method, still obscure from the point of view of the documentation requires that you install and activate the plugin OAuth1. The implementation of this authentication method includes the installation and combined use of WP-CLI, a command line for WordPress and WP Client CLI.

The introduction of command line interfaces is not a problem in itself, but it's the lack of command list that is the problem.

Service discovery

Part of learning any API is becoming familiar with its options. So I recommend you to check out the part on service discovery from the WordPress REST API documentation.

There you will find methods for interacting with articles, post types, media, metadata as well as irregularities like inability to delete a user or other minor concerns.

Remember that this is a work in progress which is already very interesting.

Who uses the WordPress REST API?

In all things there are pioneers, the WordPress REST API is no exception. Here is a short list of the few companies that make use of the API, despite its youth:

made Human use the API to build websites for customers who want something more flexible for the frontend.

WP Live Search is a free plugin that makes use of the API for its search functions.

Editus is a premium plugin which uses the API for its frontend editing functions.

According to Who's using this thing? other people and companies are implementing the WordPress REST API to build mobile applications.

Despite its youth, the WordPress REST API holds great promise as a major feature in the transformation of WordPress into an application development platform.

Are you also using the WordPress REST API?  We would like to have your impressions on the subject.

How do you find the opportunities it offers? Share your reactions with us in our comments section.

Discover also some premium WordPress plugins  

You can use other WordPress plugins to give a modern look and optimize the grip of your blog or website.

We offer you here some premium WordPress plugins that will help you do that.

1. WordPress Ultimate Redirect

The "WordPress Ultimate Redirect" plugin is the one and only solution you need to manage all your redirects, 404s, site migration and / or domain change or transfer needs.

Wordpress ultimate redirect plugin

There are plugins that do what the plugin does, but not all at the same time. This plugin provides all the usual 404 redirect functionality, plus our favorite "auto-redirect to closest URL match".

Download | Demo | Web hosting

2. Leadeo

Did you know that using a video on your Landing Page can improve conversions by more than 80%. Likewise on sales pages with more than 46%. Leadeo can help you get more leads and sales from people watching the video on your blog.Leadeo

Thanks to this plugin, you will be able to create a useful video for a targeted audience, share it on your social networks and your contact list via email, and send some advertisements. So people will see the video and enjoy it.

Since the video arouses the expected interest, those who have watched it are offered:

  • subscribe to your email list to get tips
  • contact you
  • share an interesting thing that you said in the video
  • share the video with their friends
  • click on your call to action button
  • and other

And all of these actions are offered just to the right of the video.

Download | Demo | Web hosting

3. CommentPress

CommentPress is a powerful WordPress compact plugin that lets you insert, edit and delete comments quickly and easily. CommentPress uses Ajax, jQuery and PHP to give visitors the ability to insert comments without having to reload the page.Commentpress ajax comments insert edit and delete comments

This plugin has many customization options, finally giving it the look and feel you want. It has a captcha to block spam and brings to your comment section more security.

Its main features are: the easy insertion of comments, the possibility for users to reply to specific comments, the pagination of comments, complete management of the administration of the comments section, buttons for easy insertion of images, videos and links, a fully responsive layout, a Captcha to secure the form and prevent spam, and much more.

Download | Demo | Web hosting

Recommended Resources

Find out about other recommended resources to help you build and manage your website.

Conclusion

Here! That's it for this tutorial. We hope this tutorial has shown you how to use the WordPress REST API. Feel free to share this articles with your friends on your favorite social networks

However, you will also be able to consult our resources, if you need more elements to carry out your projects of creation of Internet sites, by consulting our guide on the WordPress blog creation.

If you have suggestions or remarks, leave them in our section Comments.

... 

This article features 5 comments

  1. Bro, how can I create a model item for the rest API or model item that was created, model name, model id, json file, preview url link ? Thanks for the explanation

  2. Thanks for this article, I personally have a problem right now with REST API and Woocommerce. I am using the Secupress security plugin and some rules on the .htaccess, since then I am having problems with the LET IT BILL synchronization.

    I moved from the Legacy production environment to Stable.

    An idea ?

  3. Hello, you say to declare the header

    $ Headers = array (
    'Authorization' => 'Basic'. base64_encode ('username: password'),
    );

    but in which file please I have a little trouble understanding everything sorry

Leave a comment

Your email address will not be published. Required fields are marked with *

This site uses Akismet to reduce unwanted. Learn more about how your comments data is used.

Back To Top
11 shares
Share10
tweet1
Save