- Learning WordPress REST API
- Sufyan bin Uzayr
- 1146字
- 2021-07-14 11:00:50
Fetching GET post output in JSON objects
So far, we have seen how to GET posts and JSON objects. The preceding queries are sufficient to fetch (or GET) data for you, but how will you output the posts?
In WordPress, we often output posts by using the get_post()
function that uses the global $post
object. In a similar manner, we can use a loop that runs through all the posts retrieved by REST API and outputs them accordingly. For example, consider the following code:
$url = add_query_arg( 'per_page', 10, rest_url() ); $posts = get_json( $posts ); if ( ! empty( $posts ) ) { foreach( $posts as $post ) { ?> <article id="<?php echo esc_attr($post->ID ); ?>"> <h1><?php echo $post->title; ?></h1> <div><?php wpautop( $post->content ); ?></div> </article> <?php } //foreach }
Looking at the outcome of this loop when used within a standard function, this is how it will work (the test site has, for example, a post called Hello World!):

As you can see, the preceding code is very easy to use and we can make use of REST API to return posts and output them accordingly. The preceding code is in PHP simply because WordPress is coded in PHP. If you are coming from another programming language, the logic behind the loop will remain the same, and on the basis of methods we have already discussed in the previous chapter, you can implement it accordingly.
Issuing queries
WordPress developers generally use the WP_Query
parameters for fetching posts or issuing queries. When working with REST API in WordPress, we can still rely on a subset of WP_Query
parameters in order to query our site or other sites.
Now, on the basis of our requirements, we will need to alter the filters and parameters accordingly. For example, you may wish to query the first N number of posts, or query on the basis of post title, or query on the basis of post status (published, draft, pending review, and so on).
Once more, assuming our WordPress site is hosted at example.com
and we wish to query five posts in alphabetical order, the following is how our URL string might look like: http://example.com/wp-json/wp/v2/posts?per_page=5&order=ASC
.
But do we really need to type out URLs? No we do not. WordPress has the add_query_arg()
function that can automate the task for you. Now, if we were to pass the preceding condition or URL string to our function, the following is how it will look like:
$arg = array( 'filter[orderby]' => 'title', 'filter[per_page]' => 5, 'filter[order]' => 'ASC' ); $url = add_query_arg( $arg, rest_url( 'posts' ) );
It gets easier to use this function with jQuery's AJAX API, and we will discuss it in detail in a later chapter of this book.
Now, so far, you have learned how to issue basic queries in WordPress with REST API and have even worked with the default REST API routes in WordPress. Of course, you can make use of custom routes in REST API as well, but we shall save that discussion for a later chapter.
That said, in the previous examples, we have chosen to rely on the default post types in WordPress. What if you ever need to work with custom post types?
Basically, everything you can do with default post types in WordPress via REST API can be accomplished with custom post types as well. If you are registering or creating custom post types for your plugin or theme and you wish to add support for REST API for your custom post types, simply set the show_in_rest
variable to TRUE
. This will allow you to create routes and endpoints for REST API for that given custom post type.
On the other hand, if you wish to disallow usage of that custom post type via REST API, you can set the show_in_rest
variable to FALSE
.
That is all that you need to bear in mind with respect to custom post types. Everything else, in terms of routes and access permissions, remains the same as with default post types.
So far, you have learned how to issue basic requests in REST API over WordPress as well as how to work with request responses. However, since REST API is something that is generally used for remote access, you also need to know how to work between two different WordPress sites using REST API.
Therefore, in this section, our focus will now shift to cross-site interaction. We will learn how to copy posts from one site to another, as well as display and create posts on a remote site.
As you might have guessed by now, these actions will need POST requests and you will be passing JSON objects via these requests. In the previous section, we had setup functions for generating GET requests and URL strings. We will build upon our existing knowledge of those functions.
Issuing requests via Postman
The biggest and most obvious advantage of Postman is that it allows you to turn requests into code snippets that you can use and reuse within your code. Thus, Postman can be used to export requests as JavaScript, and that makes it the perfect fit when working with REST API for WordPress or web development.
Postman lets you send authenticated requests in a native manner. In Google Chrome, once you have installed and activated the Postman extension, you can start sending HTTP requests.
Postman supports multiple HTTP requests, and you can see that directly in the drop-down menu.

Of course, for our purpose, the GET and POST requests are the most important.
To issue an HTTP request via Postman, you need to enter the URL value and specify the parameters, if any. For instance, a GET request to a sample URL would look like as shown in the following screenshot:

The preceding requests give us raw response in HTML code. You can also see the same response in JSON, XML, or text format. However, did our GET request actually fetch our WordPress site? Simply hit the Preview link in the pane and you will see your remote WordPress site in the panel.

This is a pretty basic HTTP request and you are just fetching the WordPress site as it is. Since we will be using REST API for bigger and better queries, why not try such a request using Postman?
Say, we wish to login to our remote WordPress site. You can access the wp-admin
of your site in a similar manner.

For all practical purposes, using Postman to authenticate you via HTTP requests is possible and feasible. However, since our focus is on the usage of REST API in WordPress, let us now get started with some actual code!
HTTP API in WordPress
As the name suggests, in WordPress, the HTTP API can be used to simplify HTTP requests. It can let you make HTTP requests via PHP, either to the same site or to a different site. But more importantly, HTTP API in WordPress lets you transform URL strings into JSON objects.
Consider the following URL string: http://example.com/wp-json/wp/v2/posts
.
It is like any other URL on the Internet. Now, with HTTP API, we can convert it into a JSON object, making use of the wp_remote_get ()
function from the WordPress core:
$json = wp_remote_get ( 'http://example.com/wp-json/wp/v2/posts' );
Now, $json
will yield an array, and that is precisely the response that we need.
To understand it better, let us now put together a very small function that accepts a URL string and then gives an array of post objects:
$response = wp_remote_get( $url ); function get_json( $url ) { //GET remote site $response = wp_remote_get( $url ); //Checking for errors if ( is_wp_error( $response ) ) { return sprintf( 'Your URL %1s could not be retrieved', $url ); //GET only body $data = wp_remote_retrieve_body( $response ); } //return if no error if ( ! is_wp_error( $response ) ) { //Now, decode and return return json_decode( $response ); } }
What does the preceding code do? It makes a GET request and loads the URL string. To be sure that we are doing everything alright, we check whether our parameter is part of the WP_Error
class or not because if it is, we have encountered an error. And if it is not, we can proceed with the JSON object.
Now, to test the preceding function, you can just pass any URL string for $url
. Why not give it a shot and pass the URL to your test installation of WordPress, whatever it might be?
Ideally, the following is what your output should look like; it is pretty raw, but for a test code, this should show you that it works:
