Here are a few examples on how to use WordPress REST API v2

First of all Download and Install the plugin just like any other wordpress plugin

Get list of posts

Get list of pages

WordPress REST API for Custom Posts

Prerequisite: REST API support needs to be added to custom posts while registering the custom post.

Below parameters add the necessary support. For detailed instruction please refer Adding REST API support to Custom Post Types

Suppose we have a Custom Post Type news, below parameters would add the necessary REST support to the Custom Post Type

show_in_rest

This allows the Custom post type to be accessed through the REST API

rest_base => Optional Parameter

This allows to change the REST API route. For e.g. if the custom post type is news. We can define a custom route to access the books post using rest_base parameter e.g. news_api

rest_controller_class

This is only required to be changed if you are using a custom namespace i.e. other than wp/v2

Once the necessary support is added as shown above the Custom Post Type is ready to be accessed through the REST API

Add REST support for custom taxomonies

Add below parameters to the custom taxomony newstags

Here are a few examples for a news custom post type

Get list all posts for the custom post type news

Get first 5 posts for the custom post type news

Get list all posts for the custom post type news from a certain category

Get a single post from the custom post type news

Get posts from the custom post type news which has custom taxonomy newstags applied to it

Modify JSON Response

WordPress Rest API provides us a filter rest_prepare_{POST_NAME} to modify JSON Response i.e. to add or remove fields from the JSON response. JSON response by default include many fields which may not be necessary for you. Also it may be missing some of your custom fields.

Add a custom field

 

Leave a Reply

Your email address will not be published. Required fields are marked *