I want to show tow post meta in one rendered field rest api
my fields are 1- folder_path 2- file_name call example website/folderpath/filename.ext
i want to show it everywhere in rest api
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', 'download_link', 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 );
}
wp-json/wp/v2/posts wp-json/wp/v2/search wp-json/wp/v2/posts/ etc..
thank you
I want to show tow post meta in one rendered field rest api
my fields are 1- folder_path 2- file_name call example website/folderpath/filename.ext
i want to show it everywhere in rest api
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', 'download_link', 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 );
}
wp-json/wp/v2/posts wp-json/wp/v2/search wp-json/wp/v2/posts/ etc..
thank you
Share Improve this question asked Nov 8, 2019 at 20:19 arbfontsarbfonts 11 Answer
Reset to default 0You'll want to use the field and the post type. You'll add the following to your functions.php
add_action( 'rest_api_init', function () {
register_rest_field( '<post-type>', 'folder_path', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'folder_path', true );
},
) );
register_rest_field( '<post-type>', 'file_name', array(
'get_callback' => function( $post_arr ) {
return get_post_meta( $post_arr['id'], 'file_name', true );
},
) );
} );
- add's fields to REST API
- change
<post-type>
to your specific post-type - set the field name for the API and return the actual field itself for it (in this specific case, I just left the field_name as the meta name)