WordPress REST API and Custom Post Types

In my examples, I will be using a custom post type of “recipes”

In order to get a custom post type to show on the REST API (i.e. https://jmrowe.com/blog/wp-json/wp/v2/recipes ) , two options when using register_post_type can be set.

show_in_rest  (boolean) (optional) Whether to expose this post type in the REST API.

rest_base (string) (optional) The base slug that this post type will use when accessed using the REST API. Default: $post_type

show_in_rest must be set to true

rest_base will be the “base” of the url when calling it in the rest API.  So if nothing is set, the $post_type slug will be used.. i.e. recipes. If rest_base is changed to say “recipes-api” then to call it via the REST api it would look like: https://jmrowe.com/blog/wp-json/wp/v2/recipes-api

Sending the rest_url from WordPress to Javascript

wp_localize_script should be used to send the rest api url to javascript in a portable way such as:

 

Creating new fields in the REST responses

To add more/custom fields in the REST response. A function that does so must be added to the hook “rest_api_init” so..

register_rest_field() is used to register/add the custom field in the rest response

 

A good reference for using nonces in custom REST endpoints: https://viastudio.com/wordpress-rest-api-secure-ajax-calls-custom-endpoints/

One thing to note from this example is that WordPress suggest passing the nonce via the header and not the request content data. So, below is the better way of passing the nonce from js back to WordPress: