Book Image

Learning WordPress REST API

By : Sufyan bin Uzayr, Mathew Rooney
Book Image

Learning WordPress REST API

By: Sufyan bin Uzayr, Mathew Rooney

Overview of this book

The WordPress REST API is a recent innovation that has the potential to unlock several new opportunities for WordPress developers. It can help you integrate with technologies outside of WordPress, as well as offer great flexibility when developing themes and plugins for WordPress. As such, the REST API can make developers’ lives easier. The book begins by covering the basics of the REST API and how it can be used along with WordPress. Learn how the REST API interacts with WordPress, allowing you to copy posts and modify post metadata. Move on to get an understanding of taxonomies and user roles are in WordPress and how to use them with the WordPress REST API. Next, find out how to edit and process forms with AJAX and how to create custom routes and functions. You will create a fully-functional single page web app using a WordPress site and the REST API. Lastly, you will see how to deal with the REST API in future versions and will use it to interact it with third-party services. By the end of the book, you will be able to work with the WordPress REST API to build web applications.
Table of Contents (16 chapters)
Learning WordPress REST API
About the Authors
About the Reviewer

Issuing POST requests

So, in the previous section, we saw how to copy an existing post from a remote site to our site. However, what if we wish to create a new post directly? For that purpose, we will need to issue a POST request using the WordPress HTTP API.

We will be making use of the wp_remote_post() function that can be used to issue POST requests. As you might already be aware, if you have ever developed for WordPress, this function will ask you for two parameters: a URL to make the POST request and a corresponding array of arguments to pass along with your request. Once again, we will get an array and work with it, or if an array is not given, we will force typecast it to an array form.

To authorize the object, we will use a code that looks similar to the following:

$url = ''; 
$body = get_json( $url ); 
if ( is_object( $post ) ) { 
  $body = $post; 
  $headers = array ( 
    'Authorization' => 'Basic ' . base64_encode...