By default you can get the JSON file response when you request the JSON file with getJSON() function in WP REST API as: We have seen in this post
Introduction to Default JSON Request and Response
In WordPress, the REST API provides an interface for applications to interact with your website by sending and receiving data via JSON format. This is especially useful for developers who need to communicate with WordPress data without directly interacting with the database.
When you make a GET request to the default /wp-json/wp/v2/posts endpoint, WordPress returns a JSON array containing the default fields for each post. These fields typically include:
id: The unique identifier for the post.title: The title of the post.content: The main content of the post.excerpt: A short excerpt of the content.link: The URL to view the post.date: The date the post was published.author: The ID of the post’s author.
Here’s an example of a default JSON response:
[
{
"id": 1,
"title": "Sample Post",
"content": "<p>This is the content of the post.</p>",
"excerpt": "<p>This is an excerpt of the post.</p>",
"link": "http://example.com/sample-post",
"date": "2023-03-01T00:00:00",
"author": 1
},
{
"id": 2,
"title": "Another Post",
"content": "<p>This is another post.</p>",
"excerpt": "<p>This is an excerpt of another post.</p>",
"link": "http://example.com/another-post",
"date": "2023-03-02T00:00:00",
"author": 1
}
]
Adding Custom Fields to the REST API Response
Custom fields can be added to the WordPress REST API response using two primary methods: by registering meta fields with register_meta, or by using register_rest_field to explicitly define top-level fields.
Method 1: Using register_meta
1) Register the Custom Field:
You can register a custom field using the register_meta function. This function enables you to make this meta field accessible via the REST API.
function register_custom_meta_fields() {
register_meta('post', 'authorName', array(
'type' => 'string',
'description' => 'Name of the Author',
'single' => true,
'show_in_rest' => true,
));
}
add_action('init', 'register_custom_meta_fields');
2) Add Data to the Custom Field:
You can add custom field data using the WordPress post editor or programmatically with update_post_meta.
update_post_meta($post_id, 'authorName', 'Jane Doe');
Method 2: Using register_rest_field
1) Register the Custom Field:
You can use the register_rest_field function to add new fields to the REST API response. This method is more flexible and allows for more complex data handling.
function add_custom_rest_fields() {
register_rest_field('post', 'authorName', array(
'get_callback' => 'get_custom_field_value',
'update_callback' => null,
'schema' => array(
'description' => 'Author Name',
'type' => 'string',
'context' => array('view', 'edit'),
),
));
}
add_action('rest_api_init', 'add_custom_rest_fields');
function get_custom_field_value($object, $field_name, $request) {
return get_post_meta($object['id'], $field_name, true);
}
Accessing and Displaying the Custom Field
Once the custom field has been added to the REST API response, it can be accessed and displayed using conditional logic in your JavaScript code.
Here’s an example of how you can conditionally display the authorName custom field for posts:
fetch('http://example.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(data => {
data.forEach(item => {
// Display post details
console.log(Title: ${item.title.rendered});
console.log(Content: ${item.content.rendered});
// Conditional display of custom field
if (item.type === 'post') {
console.log(By: ${item.authorName ? item.authorName : 'Unknown Author'});
}
});
});
Detailed Practical Example
Let’s implement a detailed practical example by adding a custom field called authorName to the post type and then accessing it in front-end JavaScript.
Step 1: Register the Custom Field in PHP
Add the custom field authorName in WordPress using the register_meta method:
function register_custom_meta_fields() {
register_meta('post', 'authorName', array(
'type' => 'string',
'description' => 'Name of the Author',
'single' => true,
'show_in_rest' => true,
));
}
add_action('init', 'register_custom_meta_fields');
This code registers a custom meta field called authorName for the ‘post‘ post type, making it accessible via the REST API.
Step 2: Add Data to the Custom Field
You can add data to the authorName custom field using the WordPress post editor or programmatically with update_post_meta as follows:
update_post_meta($post_id, 'authorName', 'Jane Doe');
Once the custom field has been added to the posts, you can then access and display it using conditional logic in your front-end JavaScript code.
Accessing and Displaying the Custom Field with Conditional Logic
Below is an example of how you can conditionally display the authorName custom field for posts that have 'authorName' field. To modify the code to display the custom field only for the post type that has the custom field authorName, we can adjust the JavaScript code to check if the authorName custom field exists for each post during the iteration. Here’s the updated JavaScript code:
fetch('http://example.com/wp-json/wp/v2/posts?_embed')
.then(response => response.json())
.then(data => {
data.forEach(item => {
// Display post details
console.log(Title: ${item.title.rendered});
console.log(Content: ${item.content.rendered});
// Conditional display of custom field for posts with custom field 'authorName'
if (item['authorName'] !== undefined) {
console.log(By: ${item.authorName});
}
});
});
In this updated code, the fetch API is used to request the posts from the WordPress REST API. The URL parameter ?_embed is added to also include embedded data like author details.
Within the forEach loop, the custom field authorName is conditionally displayed only if it exists for the respective post. The if statement checks if the authorName property is defined for the item object. If it is defined, it displays the author’s name.
By updating the conditional logic in this way, the custom field authorName will be displayed only for the post type that has the custom field, providing a more precise and focused approach for displaying the custom field.
Conclusion
The process of adding custom fields to the WordPress REST API response array involves registering the custom field, adding data to the field, and then accessing and displaying it with conditional logic. By utilizing PHP to register the custom field and update its data, and JavaScript to fetch and iterate through the API response, developers can effectively customize the presentation of data based on specific criteria. With this level of control, the REST API becomes a powerful tool for tailoring the display of custom fields to ensure they are only visible for the post type in which they are relevant. This enhanced customization contributes to a more refined and targeted user experience for those interacting with WordPress data through the REST API.






