Join Morten Rand-Hendriksen for an in-depth discussion in this video Add new content to the REST API response, part of WordPress: REST API.
- [Instructor] With custom post types and taxonomies out of the way, we can focus on adding custom content to the REST API response. Adding additional content to the response is done using standard PHP and WordPress functions in a plugin or child theme, or full theme. Where exactly the code resides depends on how and where the new content will be used. If it's only going to be used by specific theme or child theme, it should probably live within that theme. If on the other hand, the content might be used by several different plugins and themes, it should live in its own plugin.
In our example, we'll place the code in a child theme, because it's custom enough that no other theme or plugin will use it. That said, the code and approach you'll learn here works just as well in a plugin. In the next chapter, we'll build a child theme off the 2017 theme, that automatically loads in the previous posts when you scroll past the current open one on single post view to create an infinite scroll-type situation. For this to work, we need to know which post is the previous post in the chronology of the site, and that piece of data is not available in the default REST API response.
So, before we build the new feature and the theme itself, we need to modify the response of the REST API to include the i.d. and title and possibly the link to the previous post. In the exercise files for this movie, 03-03, you'll find a folder called twentyseventeen-child that contains a 2017 child theme. Right now, it has only one file in it, style.css, that contains the style sheet definition and theme definition. To follow along, add the child theme to your site and activate it.
Then go to the front end, go to customize, go to header media, and just remove the header image, so that you get the exact same display as what I have.
- Using a REST client to communicate with a REST API
- Reviewing available routes, endpoints, and arguments
- Adding custom post types and taxonomies
- Altering the API response
- Using PHP for resiliency
- Passing info using wp_localize_script()
- Setting up a REST API request through AJAX
- Outputting selected post data to the front end
- Formatting post data to match a theme
- Triggering AJAX for an infinite scroll effect
- Using AJAX to load subsequent responses