Last active
October 23, 2019 17:45
-
-
Save developer-anuragsingh/d644053b6aac4f2cd3f502e5ad31e17f to your computer and use it in GitHub Desktop.
Add a new field in existing REST API's response.
This file contains hidden or 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
// Add a new field in REST API's on an existing WordPress object type. | |
// ref - https://developer.wordpress.org/reference/functions/register_rest_field/ | |
add_action( 'rest_api_init', 'create_api_posts_meta_field' ); | |
function create_api_posts_meta_field() { | |
register_rest_field( | |
'POST_TYPE', // Post type {string/array} | |
'post-meta', // Field name {string} | |
array( // Callback {array} | |
'get_callback' => 'get_post_meta_for_api', | |
'schema' => null, | |
) | |
); | |
} | |
function get_post_meta_for_api( $object ) { | |
$post_id = $object['id']; // Post's Id | |
$post_meta_fields = get_post_meta( $post_id ); // Fetch post's meta data | |
foreach( $post_meta_fields as $key => $val): | |
if($key[0] == '_') { // if meta key start with '_' found | |
unset($post_meta_fields[$key]); // remove that key from returning array | |
} | |
endforeach; | |
return $post_meta_fields; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment