Discover in this tutorial how to create an endpoint in the WordPress REST API to expose the Custom Post Type (CPT) custom fields using code.
The REST API has a number of default endpoints:
Resource | Route |
---|---|
Posts | /wp/v2/posts |
Post revisions | /wp/v2/posts/<id> |
Categories | /wp/v2/categories |
Tags | /wp/v2/tags |
Pages | /wp/v2/pages |
Page revisions | /wp/v2/pages/<id> |
Comments | /wp/v2/comments |
Taxonomies | /wp/v2/taxonomies |
Media | /wp/v2/media |
Users | /wp/v2/users |
Custom Post Type | /wp/v2/types |
Post status | /wp/v2/statuses |
Settings | /wp/v2/settings |
Themes | /wp/v2/themes |
Search | /wp/v2/search |
Blocks | /wp/v2/blocks |
Block revisions | /wp/v2/blocks/<id> |
Block rendering | /wp/v2/block-renderer |
But if you want to expose other resources you are going to have to do it manually.
For example, the other day one of OsomCode subscribers asked me how they could expose the custom fields related to a Custom Post Type.
Are you interested too?
Here’s how to do it using WordPress hooks.
Snippet to create a specific endpoint in the REST API to display the custom fields of a Custom Post Type
First of all, if the Custom Post Type is created by you, make sure you have added the argument 'show_in_rest' => true,
in the array of it, as I show you in the example to create a Custom Post Type using code.
In case you are using a third party plugin to create the CPT, if it is not supported, you can follow this tutorial on how to support the REST API in a CPT.
With this you will make sure that your CPT supports the REST API.
And now, depending on whether you are using the native WordPress custom fields or the Avanced Custom Fields plugin you will have to add one or the other of the following snippets to the end of the functions.php file or to your functionality plugin:
A – Native Custom Fields
To see this and another 997 code snippets of this website, login or subscribe here.
B – Advanced Custom Fields
To see this and another 997 code snippets of this website, login or subscribe here.
In this block you use the hook rest_api_init
to add a new endpoint to the WordPress REST API. Specifically, you get to expose all the custom fields of the Custom Post Type “Course”.
Of course, you can change the slug to that of the Custom Post Type you are interested in.
When you access the URL: https://yourwebsite.com/wp-json/cg_endpoint/v1/custom_fields/ you will see the CPT array, including its custom fields.
It will be easy to locate them as they will be followed by the text custom_fields
. For example: "custom_fields":{"price": "Free"}}
in case you have the custom field “price”.
Conclusion
Now you know how to add a specific endpoint to the WordPress REST API to display the custom fields of a Custom Post Type.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂