How to use Advanced Custom Fields and the WordPress REST API
The release of the WordPress REST API gave developers the ability to use the most popular content management system to power data-driven web and mobile applications.
When combined with Advanced Custom Fields (ACF), complex data models can be easily crafted using the familiar WordPress interface and delivered to web and mobile apps as JSON objects.
In this tutorial, you will see how to retrieve ACF data via REST endpoints using two methods:
- The ACF to REST API plugin
- A custom REST endpoint defined in functions.php
How to use the ACF to REST API Plugin
To find the URL of your REST endpoint, go to the Settings / Permalinks menu in the WordPress admin and scroll to the ACF to REST API section. You can also choose the API version (v3 is the latest at the time of this article).
Next, create a custom field group. For this example, you can create a number field called price and assigned it to all posts. Add a new post to your site, assign some values to your custom fields, and publish it.
The ACF to REST API plugin exposes endpoints for retrieving all posts, posts by ID, taxonomies, custom post types, and more.
For a full list, check out the documentation at the Github project.
You can use your browser of choice, the curl command, or (my favorite tool) Postman for testing APIs. Here is a screenshot of a GET request to the posts/ endpoint:
As you can see, the price field mentioned earlier is returned along with the post ID. If not data has been entered for that post, a value of null is returned.
How to Write a Custom WordPress REST Endpoint
You can write your own API endpoints if your site needs custom queries that can’t be implemented using the ACF to REST API plugin.
To do this, you will need to add an action to the rest_api_init hook in your theme’s function.php file. This will allow you to map a URL to a function containing your posts query.
ACF data can be added to the post data that is returned. You can loop the posts array, retrieve fields, and perform additional business logic to the requested data.
Here is an example of a custom endpoint for a custom post type:
The URL for this endpoint would be /wp-json/my_endpoint/v1/my_post_type.