Wordpress - How to get custom post meta using REST API
WP API has a rest_prepare_post
filter (or rest_prepare_CPT
if you are working with custom posts) which you can use to modify the JSON response.
In your case it will be rest_prepare_joblisting
.
function filter_joblisting_json( $data, $post, $context ) {
$phone = get_post_meta( $post->ID, '_phone', true );
if( $phone ) {
$data->data['phone'] = $phone;
}
return $data;
}
add_filter( 'rest_prepare_joblisting', 'filter_joblisting_json', 10, 3 );
Using the same filter you can also remove fields/data from the response and do any manipulation of the data.
$post
in the callback function is an array, not an object. So you cannot use $post->id
. Change it to $post['id']
and it should work:
function slug_get_phone_number($post, $field_name, $request)
{
return get_post_meta($post['id'], '_phone', true);
}
I recommend to change _phone
to phone_number
or something else without underscore prefix. Because _
is often used with private meta keys. Try to add a custom field which has meta key with _
prefix directly to your post, you will see what I meant.
Just Add this methods to function.php
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( 'tour', 'metaval', 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 the post meta
return get_post_meta( $post_id );
}