How To Extend WP REST API From Your Custom Plugin: Part 2

2 Shares

This is article 2 of 5 in the series “How To Extend WP REST API From Your Custom Plugin”

  1. How To Extend WP REST API From Your Custom Plugin (Part 1)
  2. How To Extend WP REST API From Your Custom Plugin (Part 2)

We have a basic plugin ready where we can write code. Before writing any code, let’s think that your post has a special meta key where you store the total number of post views. We need to add a new post views field to WP REST API response. There has two methods to add new field to the WP REST API response.

First, I will show you how you can register a new field to WordPress API response using register_rest_field and get or update post views. We will register the field at rest_api_init action.

Create a new file called “method-1.php” and to include it in class-rest-api-tutorial.php update the “includes” method with the following code.

Inside the “method-1.php” add the following code to register the “post_views” field.

We did not add the callback functions yet. Let’s add the callback functions.

Now, we can easily get or update the post views by sending GET or POST request to wp-json/wp/v2/posts/<post-id>

You also can use register_meta function to simply define the meta field for a particular post type.

Create another new file called “method-2.php” and to include it in class-rest-api-tutorial.php update the “includes” method with the following code.

Inside the “method-2.php” add the following code to register the post meta.

Now, we can easily get post views by sending GET request to wp-json/wp/v2/posts/<post-id>

In the next tutorial, I will show you how to extend WP REST API by adding custom endpoints.

2 Shares
%d bloggers like this: