![]() Most people are familiar with the GET method, which is what you used to read this page, as well as the POST method, which is what you use to submit data to a website. In the REST API, the same route can do different things depending on what method is used. In this case, method refers to one of the HTTP Methods. While the REST API Documentation is very good at covering this topic, I would like to add a bit more commentary and some examples.īut first, what exactly is an endpoint? An endpoint has two components: the route (URL), and the method. There are two ways of doing this: basic endpoints and the controller pattern. ![]() There will be times when you find that you need to register your own API endpoints to handle custom functionality. After a bit more explanation below, I’ll provide an example of why you might need this parameter. By default, the API will use WP_REST_Posts_Controller for all CPTs. This allows you to change the name of the class that the REST API will use to process your CPT. The final parameter, rest_controller_class, is definitely for more advanced usage. With this parameter, we now have an endpoint that looks like this: /wp-json/wp/v2/foo. By using the rest_base parameter, you can modify the endpoint to suit your needs. Suppose you want the API endpoint to be different from the registered post type for some reason. Using only the show_in_rest parameter above will give you this for an endpoint: /wp-json/wp/v2/wds_foo. The show_in_rest parameter allows the REST API to automatically detect your CPT and add it to the registered API Endpoints. 'rest_controller_class' => 'WP_REST_Posts_Controller',Įach of these parameters is optional, and you will typically only ever need to use show_in_rest. When registering your CPT, you can add a few parameters to the register_post_type() function call: One of the most common way to create custom data in WordPress is to create a Custom Post Type (CPT). When utilizing CPTs, it is very easy to ensure that your data is accessible via the API. For a good explanation of how to use register_rest_field(), as well as example usage, it will be helpful to refer to the REST API Documentation. ![]() If you want to add this custom post meta to the default API output for a post, this is easy to do with register_rest_field(). This tutorial aims to explain those methods and provide useful examples.Ī common way to add custom data to WordPress is to utilize post meta (preferably using CMB2!). ![]() There are a number of methods that you can use to expose your data via the API. When working with custom content in WordPress, it is likely that you will come to a point where you want to retrieve that custom data via the WordPress REST API. We have had a number of API posts in the past, and now we want to cover custom API endpoints more thoroughly. Here at WDS, we’re expanding our usage of the WP API. ![]()
0 Comments
Leave a Reply. |