WordPress Register new REST field
Last Updated :
09 Nov, 2022
Registering a new rest field in your API response makes your API more detailed. You do not need to create another endpoint for getting those values.
Let’s say you’re working with WordPress posts. By default, WordPress provides all the needed data in the post-API response. But what if you want to add other data maybe your custom integration data or third-party integration data? At that time we can register a new REST field in the object.
See the below example. We have registered a field name post-meta-fields in our post response:
Steps to register the new rest field: You must add this code to the theme’s functions.php file.
Step 1: Create a function that registers the REST field with the register_rest_field() function.
This function’s first parameter is an object name, which means in which object you want to add REST fields like the post, term, comment, etc. The second parameter is the field name that you want to keep. The third parameter is an array of arguments like callback function and schema.
PHP
<? php
function register_all_post_meta_field() {
register_rest_field(
'post' ,
'post-meta-fields' ,
array (
'get_callback' => 'get_all_post_meta' ,
'schema' => null,
)
);
}
?>
|
Step2: Create callback function get_all_post_meta().
In this function, we will add our custom code, like what we want to show in the post-meta-fields field. The value could be any like integer, string, array, etc.
PHP
<?php
function get_all_post_meta( $object ) {
$post_id = $object [ 'id' ];
return get_post_meta( $post_id );
}
?>
|
Step3: Add action hook rest_api_init which will run our function register_all_post_meta_field on initialization of REST API on WordPress.
PHP
<?php
add_action( 'rest_api_init' , 'register_all_post_meta_field' );
?>
|
Complete Code: Below given the whole steps in one frame.
PHP
<? php
add_action( 'rest_api_init' , 'register_all_post_meta_field' );
function register_all_post_meta_field() {
register_rest_field(
'post' ,
'post-meta-fields' ,
array (
'get_callback' => 'get_all_post_meta' ,
'schema' => null,
)
);
}
function get_all_post_meta( $object ) {
$post_id = $object [ 'id' ];
return get_post_meta( $post_id );
}
?>
|
Output:
Hope this will be helpful!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...