php - Get multiple post meta with WordPress REST API

235
function my_rest_prepare_post( $data, $post, $request ) {
   $_data = $data->data;
   $_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
   $data->data = $_data;
   return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );

Above is the code I am using to include meta value in API. But I want to include multiple meta I tried adding different meta key separating with, inmy_custom_field_key but I displayed only first key's value.

And second problem it only displayed Meta value how can I include key:value in JSON response?

651

Answer

Solution:

Modifying my accepted answer in this similar question, I've tested the working function in my local site.

add_action( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields() {
register_rest_field(
'post', 
'custom_fields', //New Field Name in JSON RESPONSEs
array(
'get_callback'    => 'get_custom_fields', // custom function name 
'update_callback' => null,
'schema'          => null,
 )
);
}

Then define your functions to get custom fields

function get_custom_fields( $object, $field_name, $request ) {
return get_post_meta( $object['id'] );
}
57

Answer

Solution:

//returns an array of metadata get_metadata('post', $post->ID)

https://codex.wordpress.org/Function_Reference/get_metadata

People are also looking for solutions to the problem: php - Prepared statement not sending

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.