Created
October 17, 2018 17:15
-
-
Save junaidtk/942d026d3228241f274254db2a124ab7 to your computer and use it in GitHub Desktop.
How to add meta field to REST API Response of a WordPress Posts using register_rest_field?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can use the register_rest_field() function to add additional meta key to the REST API | |
eg: | |
add_action( 'rest_api_init', 'create_api_posts_meta_field' ); | |
function create_api_posts_meta_field() { | |
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() ) | |
register_rest_field( 'post', 'banner_image', array( | |
'get_callback' => 'get_post_meta_for_api', | |
'schema' => null, | |
) | |
); | |
} | |
function get_post_meta_for_api( $object ) { | |
//get the id of the post object array | |
$post_id = $object['id']; | |
return get_post_meta( $post_id ); | |
} | |
By using this code you will get the API response contain the key as "banner_image" and value contain the meta data of the post. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment