Here at WDS, we’re expanding our usage of the WP API. We have had a number of API posts in the past, and now we want to cover custom API endpoints more thoroughly. 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. There are a number of methods that you can use to expose your data via the API. This tutorial aims to explain those methods and provide useful examples. Post Meta A common way to add custom data to WordPress is to utilize post meta (preferably using CMB2!). 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(). 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. Adding Custom Post Types 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. When registering your CPT, you can add a few parameters to the register_post_type() function call: $args = array(// other args...'show_in_rest'=>true,'rest_base'=>'foo','rest_controller_class'=>'WP_REST_Posts_Controller',);
Share This