Creating a Custom REST API Route in WordPress

You’ve probably heard of the acronym “API”, which as a digital marketer, you’ll come across any time you’re working to connect two different platforms to each other.

API stands for “Application Programming Interface” and is a set of standards and protocols that allows different software applications to share data between them.

You may also come across also what’s called a REST API – a “REpresentational State Transfer” – which is an architectural style that defines a set of constraints and allows different applications to communicate over HTTP.

WordPress comes with a built-in REST API and also a rich set of tools for creating new ones and updating existing ones.

Why would you use this? Let’s say that your WordPress-powered website has a library of books created as a custom post type, and you want to be able to make that data easily available to a third-party platform or service that wants to use and display that data for their own purposes.

Here’s what you’d do.

Ensure Your Custom Post Type Displays in the REST API

When you’re registering your custom post type of “Books”, you need to add a parameter to the register_post_type() function called “show_in_rest”, and set its value to “true”. This tells WordPress that the custom post type should be displayed in the WordPress REST API.

register_post_type("books",
     array(
          …,
          …,
          "show_in_rest" => true,
     )
);

After adding the “show_in_rest” parameter, you’ll be able to see all of the “Book” posts and all of the public fields by accessing this link (customized for your website and custom post type name): https://www.yourwebsite.com/wp-json/wp/v2/books

If you’re planning to provide all of the public fields for every one of your “Books”, then this URL works perfectly for the third-party platform to use.

Create a Custom API Route for Sharing Specific Content

If you want to control exactly which posts or which fields are made available in the API, then you need to create a Custom API Route, which limits the content shared based on your logic.

You could potentially create a custom taxonomy for the “Books” post type, or you could use a custom field that sets whether or not the post should be added to the API. For this example, we’ll add the custom field – which can be done either by using add_post_meta() or adding a toggle with Advanced Custom Fields. Let’s add a custom field named “send_to_third_party” which, when its value is “1”, means it will be added to the API.

Once we have the custom field in place, let’s create a custom API Route for the third-party so they can access only the relevant “Books” posts.

add_action('rest_api_init', function () {
     register_rest_route('thirdparty/v1', '/books/', array(
          'methods' => 'GET',
          'callback' => 'dgtlnk_thirdparty_api_data',
          'permission_callback' => '__return_true',
     ));
});

In the above code, we use the rest_api_init action hook and register a new API Route at https://www.yourwebsite.com/wp-json/thirdparty/v1/books. We set the method to access the API Route as “GET” so anyone accessing the Route can only view the information – they are not able to make any updates or delete any content. We set the “permission_callback” parameter to return true so we don’t need any authentication to access the Route. Finally, we add a callback function that is used to populate the data when the Route is accessed.

Query the Content for the REST API Call

Now that we have our post type registered, our custom field added to choose which content should be shared, and the API Route created, it’s time to create a pretty JSON formatted response with the data we’re making available.

In this callback function, we’re going to query the “Books” custom post type, look for the content where the “send_to_third_party” custom field has a value of “1”, and then create an array that contains the post’s ID, Title and Content.

After looping through all the posts, we’ll use the rest_ensure_response() function to display the $data array in a JSON format when the Route is accessed.

function dgtlnk_thirdparty_api_data(WP_REST_Request $request) {
     $thirdparty_query = new WP_Query(array(
          'post_type'      => 'books',
          'posts_per_page' => -1,
          'post_status'    => 'publish',
          'meta_query' => array(
               array(
                    'key' => 'send_to_third_party',
                    'value' => 1)
               )
          ));
     $data  = array();
     if ($thirdparty_query->have_posts()) {
          while($thirdparty_query->have_posts()) {
          $thirdparty_query->the_post();
          $data[] = array(
               "id" => get_the_id(),
               "title" => get_the_title(),
               "content" => get_the_content()
               );
          }
     }
     wp_reset_postdata();
     return rest_ensure_response($data);
}

Now, if you visit the REST Route we created, you’ll only see “Books” posts that have the “send_to_third_party” custom field value set to “1”.

With this code, we can enable a custom REST API Route and easily control what gets displayed. If you also need help implementing a custom REST API Route or for any other digital marketing needs, reach out to us.