Created
October 17, 2018 17:03
-
-
Save junaidtk/278ef494704c0694a27e7e5031f364c3 to your computer and use it in GitHub Desktop.
How to add meta field to REST API Response of a WordPress Posts using register_meta ?
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 two methods for adding the new meta field to Rest API. By using register_meta() function and register_rest_field() function. | |
1)register_meta() function. | |
By using this function you can add additional meta key to API response by adding the 'show_in_rest' => true, parameter to arguments. | |
eg: | |
$object_type = 'post'; | |
$args1 = array( // Validate and sanitize the meta value. | |
// Note: currently (4.7) one of 'string', 'boolean', 'integer', | |
// 'number' must be used as 'type'. The default is 'string'. | |
'type' => 'string', | |
// Shown in the schema for the meta key. | |
'description' => 'A meta key associated with a string meta value.', | |
// Return a single value of the type. | |
'single' => true, | |
// Show in the WP REST API response. Default: false. | |
'show_in_rest' => true, | |
); | |
register_meta( $object_type, 'meta_key_name', $args1 ); | |
By using this method you can see the meta key added in the API Json reponse. You can check by usnig the URL | |
http://site_url.com/wp-json/wp/v2/posts/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment