- The article explains how to expose custom fields of a custom post type to the REST API in WordPress, using two methods: registering the custom fields with the show_in_rest argument, and using the register_rest_field function.
- The article provides examples to illustrate the process, and compares the pros and cons of each method.
WordPress is a powerful and flexible platform that allows you to create and manage different types of content using custom post types and custom fields. Custom post types are user-defined content types that extend the default WordPress post types, such as posts, pages, media, etc. Custom fields are additional metadata that you can add to any post type to store extra information, such as price, rating, location, etc.
However, if you want to access or modify your custom post types and custom fields using the WordPress REST API, you may encounter some challenges. By default, the WordPress REST API does not expose custom fields of any post type, unless they are registered with the show_in_rest argument set to true. This means that you cannot retrieve or update the custom field values using the REST API endpoints.
In this article, we will show you how to expose custom fields of a custom post type to the REST API in WordPress, using two methods: registering the custom fields with the show_in_rest argument, and using the register_rest_field function. We will also provide some examples and screenshots to illustrate the process.
Table of Contents
- Method 1: Registering Custom Fields with the show_in_rest Argument
- Method 2: Using the register_rest_field Function
- Frequently Asked Questions (FAQ)
- Question: How can I get the value of a custom field in PHP?
- Question: How can I update the value of a custom field in PHP?
- Question: How can I delete a custom field in PHP?
- Question: How can I expose other types of data to the REST API in WordPress?
- Conclusion
Method 1: Registering Custom Fields with the show_in_rest Argument
The first method to expose custom fields of a custom post type to the REST API is to register them with the show_in_rest argument set to true. This argument tells WordPress whether the custom field should be included in the REST API response for the post type.
To use this method, you need to have access to the code where you register your custom post type and custom fields. This could be in your theme’s functions.php file, or in a plugin file. You also need to know the name (or slug) of your custom post type and custom fields.
Here are the steps to follow:
- Locate the code where you register your custom post type using the register_post_type function. For example, let’s say you have a custom post type called product, and you register it like this:
function my_custom_post_type() {
$args = array(
'label' => 'Products',
'public' => true,
'show_in_rest' => true,
// other arguments
);
register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_type' );
Notice that we have already set the show_in_rest argument to true for the custom post type. This is necessary for the REST API to recognize and expose the custom post type.
- Locate the code where you register your custom fields using the register_meta function. For example, let’s say you have two custom fields called _price and _rating, and you register them like this:
function my_custom_fields() {
register_meta( 'post', '_price', array(
'type' => 'number',
'single' => true,
'show_in_rest' => false,
// other arguments
) );
register_meta( 'post', '_rating', array(
'type' => 'number',
'single' => true,
'show_in_rest' => false,
// other arguments
) );
}
add_action( 'init', 'my_custom_fields' );
Notice that we have set the show_in_rest argument to false for both custom fields. This means that they will not be exposed to the REST API by default.
- Change the show_in_rest argument to true for each custom field that you want to expose to the REST API. For example, if we want to expose both _price and _rating, we can change the code like this:
function my_custom_fields() {
register_meta( 'post', '_price', array(
'type' => 'number',
'single' => true,
'show_in_rest' => true,
// other arguments
) );
register_meta( 'post', '_rating', array(
'type' => 'number',
'single' => true,
'show_in_rest' => true,
// other arguments
) );
}
add_action( 'init', 'my_custom_fields' );
- Save your changes and test your REST API endpoints. You can use a tool like Postman or Insomnia to send HTTP requests to your endpoints and view the responses. For example, if we send a GET request to /wp-json/wp/v2/product, we should see something like this:
Notice that we can see both _price and _rating in the meta object of each product.
Similarly, if we send a POST or PUT request to /wp-json/wp/v2/product/<id>, we can update the custom field values by passing them in the meta object of the request body. For example, if we send a PUT request to /wp-json/wp/v2/product/123 with the following body:
{
"meta": {
"_price": 99.99,
"_rating": 4.5
}
}
Notice that the _price and _rating values have been updated in the response.
This method is relatively simple and straightforward, but it has some limitations. For example, you cannot customize the name or format of the custom fields in the REST API response, and you cannot add any validation or sanitization logic to the custom fields. If you need more control and flexibility over your custom fields, you can use the second method.
Method 2: Using the register_rest_field Function
The second method to expose custom fields of a custom post type to the REST API is to use the register_rest_field function. This function allows you to add or modify any field in the REST API response for any post type.
To use this method, you need to have access to the code where you register your custom post type and custom fields, as well as the code where you hook into the rest_api_init action. You also need to know the name (or slug) of your custom post type and custom fields.
Here are the steps to follow:
- Locate the code where you register your custom post type using the register_post_type function, and make sure that you set the show_in_rest argument to true. This is the same as in method 1.
- Locate the code where you register your custom fields using the register_meta function, and make sure that you set the show_in_rest argument to false. This is also the same as in method 1.
- Hook into the rest_api_init action and use the register_rest_field function to add or modify any field in the REST API response for your custom post type. For example, let’s say we want to expose both _price and _rating as separate fields in the response, and we want to rename them as price and rating. We can do something like this:
function my_custom_rest_fields() {
register_rest_field( 'product', 'price', array(
'get_callback' => 'get_price_field',
'update_callback' => 'update_price_field',
'schema' => array(
'description' => 'The product price',
'type' => 'number'
)
) );
register_rest_field( 'product', 'rating', array(
'get_callback' => 'get_rating_field',
'update_callback' => 'update_rating_field',
'schema' => array(
'description' => 'The product rating',
'type' => 'number'
)
) );
}
add_action( 'rest_api_init', 'my_custom_rest_fields' );
Notice that we have specified three arguments for each field: get_callback, update_callback, and schema. The get_callback is a function that returns the value of the field for each product. The update_callback is a function that updates the value of the field when a product is created or modified. The schema is an array that describes the field’s properties, such as description, type, etc.
- Define your callback functions for each field. For example, we can define our functions like this:
function get_price_field( $object, $field_name, $request ) {
return get_post_meta( $object['id'], '_price', true );
}
function update_price_field( $value, $object, $field_name ) {
if ( ! $value || ! is_numeric( $value ) ) {
return;
}
return update_post_meta( $object->ID, '_price', $value );
}
function get_rating_field( $object, $field_name, $request ) {
return get_post_meta( $object['id'], '_rating', true );
}
function update_rating_field( $value, $object, $field_name ) {
if ( ! $value || ! is_numeric( $value ) || $value < 0 || $value > 5 ) {
return;
}
return update_post_meta( $object->ID, '_rating', $value );
}
Notice that we have added some validation and sanitization logic to our update callbacks, such as checking if the value is numeric, or if it is within a certain range.
- Save your changes and test your REST API endpoints.
You can use a tool like Postman or Insomnia to send HTTP requests to your endpoints and view the responses. For example, if we send a GET request to /wp-json/wp/v2/product.
Notice that we can see both price and rating as separate fields in the response.
Similarly, if we send a POST or PUT request to /wp-json/wp/v2/product/<id>, we can update the field values by passing them in the request body. For example, if we send a PUT request to /wp-json/wp/v2/product/123 with the following body:
{
"price": 99.99,
"rating": 4.5
}
Notice that the price and rating values have been updated in the response.
This method is more flexible and powerful than the first method, as it allows you to customize the name, format, validation, and sanitization of your custom fields in the REST API response. However, it also requires more coding and testing, and it may not be compatible with some plugins or themes that rely on the default meta fields.
Frequently Asked Questions (FAQ)
Here are some common questions and answers related to exposing custom fields of a custom post type to the REST API in WordPress.
Question: How can I get the value of a custom field in PHP?
Answer: You can use the get_post_meta function to get the value of a custom field for any post type in PHP. For example, if you want to get the value of _price for a product with ID 123, you can do something like this:
$price = get_post_meta( 123, '_price', true );
The first argument is the post ID, the second argument is the meta key (or custom field name), and the third argument is whether to return a single value or an array of values.
Question: How can I update the value of a custom field in PHP?
Answer: You can use the update_post_meta function to update the value of a custom field for any post type in PHP. For example, if you want to update the value of _rating for a product with ID 123, you can do something like this:
update_post_meta( 123, '_rating', 4.5 );
The first argument is the post ID, the second argument is the meta key (or custom field name), and the third argument is the new meta value.
Question: How can I delete a custom field in PHP?
Answer: You can use the delete_post_meta function to delete a custom field for any post type in PHP. For example, if you want to delete _price for all products, you can do something like this:
delete_post_meta_by_key( '_price' );
The only argument is the meta key (or custom field name) that you want to delete.
Question: How can I expose other types of data to the REST API in WordPress?
Answer: You can use the same methods that we have discussed in this article to expose other types of data to the REST API in WordPress, such as taxonomies, terms, users, comments, etc. You just need to use different functions and hooks depending on the data type. For example, if you want to expose a custom taxonomy called genre to the REST API, you can use something like this:
function my_custom_taxonomy() {
$args = array(
'label' => 'Genres',
'public' => true,
'show_in_rest' => true,
// other arguments
);
register_taxonomy( 'genre', 'post', $args );
}
add_action( 'init', 'my_custom_taxonomy' );
Or if you want to expose a user meta field called _bio to the REST API, you can use something like this:
function my_custom_user_field() {
register_rest_field( 'user', 'bio', array(
'get_callback' => 'get_bio_field',
'update_callback' => 'update_bio_field',
'schema' => array(
'description' => 'The user bio',
'type' => 'string'
)
) );
}
add_action( 'rest_api_init', 'my_custom_user_field' );
Conclusion
In this article, we have shown you how to expose custom fields of a custom post type to the REST API in WordPress, using two methods: registering the custom fields with the show_in_rest argument, and using the register_rest_field function. Both methods have their pros and cons, and you can choose the one that suits your needs and preferences.
We hope that this article has been helpful and informative for you. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!
Disclaimer: The content of this article is for informational purposes only and does not constitute legal or professional advice. The author is not a lawyer and does not claim to provide any legal services or representation. The information and opinions expressed in this article are based on the author’s personal research and experience, and may not reflect the current state of the law or the views of any other person or entity. The author is not responsible for any errors, omissions, or consequences that may arise from the use or reliance on the information or opinions in this article. Readers are advised to consult a qualified lawyer or professional before taking any action based on the content of this article. The author does not endorse or guarantee any products, services, or websites that may be mentioned or linked in this article.