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
Credits
About the Authors
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface

Interacting REST API via PHP


Let us now learn how to copy posts from one site to another site. Basically, we will be using REST API to GET JSON post data and convert it into a PHP object. In the previous section, we have already created a function for this and we will reuse the code. It is as simple as passing the following request:

$url = 'http://example.com/wp-json/wp/v2/posts/1'; 
$post = get_json( $url ); 

Now, to create a copy of the post, we just have to turn $post into an array and then pass it to wp_insert_post().

To convert $post, we will follow a standard web development practice. Before the code, let us first spend some time understanding what we need to do.

Explanation of function

As already stated, we have to ensure that the data being passed to the function is an array. If the data is an object, we will need to typecast it as an array because the rest of the function will require an array.

Thereafter, once we have an array, we will setup a second array because we will...