- Learning WordPress REST API
- Sufyan bin Uzayr
- 763字
- 2021-07-14 11:00:48
Getting started
First up, you will need to set up your WordPress website. Obviously, you should not use a production site for learning purposes; therefore, I will strongly advise you to set up a test installation of WordPress for experimenting and playing with REST API. Depending on your mode of operation, you may choose to do it the way it suits you—some developers prefer having a local version of WordPress running on their device, whereas others, such as myself, set up WordPress live on a test server and access it accordingly.
You might also do it via Vagrant, if that suits you.
You may then install the WordPress REST API plugin much like any other normal plugin. Find the latest version at https://wordpress.org/plugins/rest-api/.
That said, let us get started with REST requests in WordPress. As we have seen in the last chapter, REST requests generally revolve around the four common HTTP transport methods: GET, PUT, POST, and DELETE. Plus, we have also learned that GET and POST requests are used to obtain data and to update data, respectively.
Furthermore, we are, by now, aware that RESTful requests are pretty simple in nature, and it is only a matter of passing the right URL string as the parameter in order to make GET or POST queries. You can directly pass the URL strings, or place them within functions, or use a service or tool such as Postman to do it. In this chapter, we will be discussing all three methods.
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.
- SOA實(shí)踐
- Mastering Articulate Storyline
- 網(wǎng)頁(yè)設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- Julia Cookbook
- Learning Network Forensics
- Swift語(yǔ)言實(shí)戰(zhàn)精講
- Instant Nancy Web Development
- INSTANT Sinatra Starter
- Service Mesh實(shí)戰(zhàn):基于Linkerd和Kubernetes的微服務(wù)實(shí)踐
- Kotlin開(kāi)發(fā)教程(全2冊(cè))
- Mastering AWS Security
- Python商務(wù)數(shù)據(jù)分析(微課版)
- JQuery風(fēng)暴:完美用戶體驗(yàn)
- 零基礎(chǔ)看圖學(xué)ScratchJr:少兒趣味編程(全彩大字版)
- C++ System Programming Cookbook