Notes

WordPress API - send post details with comments data

Edit on GitHub

ReactJS
2 minutes

Why?

I need the post title and slug in the comments endpoint so that i don’t have to make another call to get that data to build the post title link.

Username commented on Post title

There are two ways you can do this:

  • Add a new field with register_rest_field
  • Edit the response that is sent using the rest_prepare_comment filter

register_rest_field()

  • The rest_api_init action fires when preparing to serve an API request
  • The register_rest_field() registers a new field on an existing WordPress object type (post, comment etc.)
 1//
 2// Add post slug to the /comments/ endpoint
 3// so that we don't have to make another call to get the post title and slug to build the URLs
 4//
 5add_action('rest_api_init', function () {
 6	// register_rest_field( $object_type, $attribute, $args)
 7	register_rest_field('comment', 'post_slsug', array(
 8		'get_callback' => function ($comment) {
 9												$post = get_post($comment['post']);
10												return $post->post_name;
11											}
12	));
13});

The same can be written like so:

 1//
 2// Add post title to the /comments/ endpoint
 3// so that we don't have to make another call to get the post title and slug to build the URLs
 4//
 5add_action('rest_api_init', function () {
 6	// register_rest_field( $object_type, $attribute, $args)
 7	register_rest_field('comment', 'post_title', array(
 8		'get_callback' => send_post_title_with_comments
 9	));
10});
11
12
13// get_callback()
14// this is the data we'll send when somebody calls the endpoint
15function send_post_title_with_comments ($comment_array) {
16	$comment_object = get_comment($comment_array['id']);
17
18	return $comment_object -> post_title; // send back post_title
19}

rest_prepare_comment()

The rest_prepare_comment() hook lets you modify the comment right before it is returned.

 1function send_post_details ($response, $comment, $request) {
 2	$parent_post = get_post($response -> data['post']);
 3	$title = $parent_post -> post_title;
 4	$slug = $parent_post -> post_name;
 5
 6	$response -> data['post_title'] = $title;
 7	$response -> data['post_slug'] = $slug;
 8
 9	return $response;
10};
11// https://developer.wordpress.org/reference/hooks/rest_prepare_comment/
12add_filter( 'rest_prepare_comment', 'send_post_details', 10, 3);