Here is a quick tutorial that explains how to add a custom field to WordPress REST results. Estimated time required: 5 minutes.
Step 1: Gather info
Before adding the code snippet, make sure you have the following information:
- The name of the custom field that you want to add to REST
- The name of the field/attribute that should be included in REST results
Once you’ve got that much, continue to Step 2.
Step 2: Add code
Next, add the following code snippet to your theme’s functions.php
file (or you can make a simple plugin if preferred):
function usp_pro_get_custom_field($post, $field, $request) {
return get_post_meta($post, 'usp-custom-1', true); // custom field name
}
function usp_pro_rest_add_custom_field() {
register_rest_field(
'post',
'usp_custom_field', // rest field name
array(
'get_callback' => 'usp_pro_get_custom_field',
'update_callback' => null,
'schema' => null,
)
);
}
add_action('rest_api_init', 'usp_pro_rest_add_custom_field');
Now grab the two items from Step 1, above. In the previous code snippet, replace the following:
- In the first function, replace
usp-custom-1
with the name of your custom field - In the second function, replace
usp_custom_field
with the name of your REST field/attribute
That’s all there is to it. Upload, test, and done. Of course, this tutorial just shows the basics to help get you started. From here, you may customize things however is desired. Much is possible with the WP REST API.
How the code works
In the previous code, there are two functions. The first is simply a callback function that returns the single value of your chosen custom field. The second function uses register_rest_field() to add the custom field to the REST output. Pretty much that’s it, but again, much more is possible with WordPress :)