- Learning WordPress REST API
- Sufyan bin Uzayr
- 1321字
- 2021-07-14 11:00:50
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 = 'http://example.com/wp-json/wp/v2/posts/1'; $body = get_json( $url ); if ( is_object( $post ) ) { $body = $post; $headers = array ( 'Authorization' => 'Basic ' . base64_encode( 'admin' . ':' . 'password' ), ); $remote_url = 'http://example-remote.com/wp-json/wp/v2/posts'; }
Here, the example remote.com
is the remote site URL.
In the preceding code sample, we are first getting an object and then verifying if it truly is an object. Once verified, we just need to setup headers for authentication and provide the authentication details. Next, we are putting the URL for the endpoint of the post of the remote site in $remote_url
so that we can actually make the POST request.
What next? We will carry on with the preceding code and send the request to wp_remote_post()
, along with the required arguments as follows:
//Authentication $url = 'http://example.com/wp-json/wp/v2/posts/1'; $body = get_json( $url ); if ( is_object( $post ) ) { $body = $post; $headers = array ( 'Authorization' => 'Basic ' . base64_encode( 'admin' . ':' . 'password' ), ); $remote_url = 'http://example-remote.com/wp-json/wp/v2/posts'; } $headers = array ('Authorization' => 'Basic ' . base64_encode( 'admin' . ':' . 'password' ), ); //Copying response $response = wp_remote_post( $remote_url, array ( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => $headers, 'body' => json_encode( $post ), 'cookies' => array () ) ); //Checking if error occurred. if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); echo sprintf( '<p>Error: %1s</p>', $error_message ); } else { echo 'Response:<pre>'; print_r( $response ); echo '</pre>'; } } else { $error_message = 'Data invalid!'; echo sprintf( '<p>Error: %1s</p>', $error_message ); }
Once you run the preceding code, your remote site will return a success code in the header, meaning that the POST request completed successfully. For HTTP requests, 200OK is the standard response that means everything went alright. If not, you will be presented with an error with details of that error.
On successful completion of the code request, the response code will look like as shown in the following screenshot:

We will now turn our attention towards post meta fields in WordPress. Every WordPress developer is aware of the role of post metadata in development. However, how do we work with, retrieve, or update post metadata in WordPress using REST API? The following section will answer the question.
Also, note that while the following has been written with post metadata and meta fields in mind, the logic can easily be applied to user metadata and meta fields as well.
Implementing GET meta fields using REST API in WordPress
First up, let us start with GET requests. So far, we have been issuing GET requests to fetch posts via REST API. However, with such queries, the post meta fields are not included.
Now, in order to successfully GET post meta fields using REST API, we will need an endpoint with authentication.
Let us try to understand this with an example. Say, we have a post type called painter
, and an associated meta field named water_color
. Now, say we wish to pass a GET request to wp-json/wp/v2/painter
, and with the results, we also want to GET the value held by the water_color
field.
For this purpose, we can use the register_api_field()
function that can add an extra meta field to the response. This function will require three arguments: the first, obviously, will be the post type for which we need to add the field for, the second will be the name of the meta field, and the third will be the array of arguments wherein you can define the callback method to GET or POST the value of the meta field.
To begin, let us set some callback methods:
function get_post_meta_clbk( $object, $field_name, $request ) { return get_post_meta( $object[ 'id' ], $field_name ); } function update_post_meta_clbk( $value, $object, $field_name ) { return update_post_meta( $object[ 'id' ], $field_name, $value ); }
And now, we can simply register our API fields, as follows:
add_action( 'rest_api_init', function() { register_api_field( 'painter', 'water_color', array( 'get_callback' => 'get_post_meta_clbk', 'update_callback' => 'update_post_meta_clbk', 'schema' => null, ) ); });
After this, each time you make a GET request to wp-json/wp/v2/painter
, you will also be given the value of the corresponding meta field. The following is how it might look in the raw output:

And in the proper preview mode, it will look like the following:

Note
Note that the preceding GET requests will work only if the values of the meta fields are unprotected. For protected meta fields (in WordPress, they generally begin with an underscore (_)
), the method is different, and we shall turn to that method now.
Implementing POST meta fields using REST API in WordPress
In our previous example, we saw how to get the value for the water_color
field for a post type painter. Now, what if we wish to edit or create new value for that meta field?
Much like working without REST API, we need to find the meta ID for the given meta field and then pass that meta ID in order to tell WordPress that we wish to make changes or update the values for the concerned meta ID.
Thus, assuming that the meta ID is 10
for the post type ID 1
, we will pass the POST request as such: wp-json/wp/v2/painter/01/meta/10
.
Now, we can create the meta field and then issue the relevant requests, as shown in the following code:
//GET URL request $url = rest_url( 'wp/v2/posts/1/meta' ); //ADD basic headers for authentication $headers = array ( 'Authorization' => 'Basic ' . base64_encode( 'admin' . ':' . 'password' ), ); //ADD meta value to body $body = array( 'key' => 'water_color', 'value' => 'blue' ); //POST request $response = wp_remote_request( $url, array( 'method' => 'POST', 'headers' => $headers, 'body' => $body ) ); //if no error, we GET ID of meta key $body = wp_remote_retrieve_body( $response ); if ( ! is_wp_error( $body ) ) { $body = json_decode( $body ); $meta_id = $body->id; echo $body->value; if ( $meta_id ) { //ADD meta ID to URL $url .= '/' . $meta_id; //SEND value $body = array( 'value' => 'blue' ); $response = wp_remote_request( $url, array( 'method' => 'POST', ) ); 'headers' => $headers, 'body' => $body //if no error, then echo the value $body = wp_remote_retrieve_body( $response ); if ( ! is_wp_error( $body ) ) { $body = json_decode( $body ); echo $body->value; } } }
If the preceding code runs well, you will get status code 200
, which implies that all is fine with your HTTP request, as shown in the following screenshot:

What are we doing in the preceding code? We are issuing requests to get the meta field value, and then editing it and passing the updated value. Simple!
As you can see from the preceding example, we can use the register_api_field()
function to work with meta fields and update any type of value we want. As you progress with REST API in WordPress, you will notice that it is one of the most crucial functions when working with REST API.
- Mastering Visual Studio 2017
- jQuery EasyUI網站開發實戰
- Java虛擬機字節碼:從入門到實戰
- 編寫高質量代碼:改善C程序代碼的125個建議
- HTML5+CSS3網頁設計
- Getting Started with NativeScript
- 基于Struts、Hibernate、Spring架構的Web應用開發
- Learning Apache Cassandra
- RESTful Java Web Services(Second Edition)
- Fast Data Processing with Spark(Second Edition)
- C++語言程序設計
- UI動效設計從入門到精通
- JavaScript Mobile Application Development
- Azure for Architects
- 計算機視覺實戰:基于TensorFlow 2