Notes

Customizing WordPress API data

Edit on GitHub

PHP
4 minutes

What i want:

  • remove unnecessary data from the response (e.g. _links)
  • add data from multiple endpoints to one response so that i don’t have to call multiple endpoints (e.g. featured image size URLs)
  • customize the data that is sent back (e.g. excerpts)

Notes:

  • The complete REST response is filtered through rest_prepare_post filter. It allows modification of the post type data right before it is returned.
  • Action hooks look like this: do_action( "hook_name" )
  • Filter hooks look like this: apply_filters( "hook_name", "what_to_filter" ).

add_filter

Hooks a function or method to a specific filter action.

1// add_filter parameter
2add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

Examples

 1// Add Featured Image source URLs to the `/posts/` endpoint response
 2
 3function add_featured_image_url ($data, $post, $context) {
 4	$featured_image_id = $data -> data['featured_media']; // get featured image ID from $data
 5	$featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // get URL of original size
 6	$featured_image_url_thumbnail = image_get_intermediate_size( $featured_image_id, 'thumbnail' ); // get URL of thumbnail size
 7	$featured_image_url_medium = image_get_intermediate_size( $featured_image_id, 'medium' ); // get URL of medium size
 8
 9	if ( $featured_image_url_thumbnail ) {
10		$data -> data['featured_image_url']['thumbnail'] = $featured_image_url_thumbnail['url'];
11	}
12
13	if ( $featured_image_url_medium ) {
14		$data -> data['featured_image_url']['medium'] = $featured_image_url_medium['url'];
15	}
16
17	if ( $featured_image_url ) {
18		$data -> data['featured_image_url']['full'] = $featured_image_url[0];
19	}
20
21	return $data;
22}
23
24add_filter( 'rest_prepare_post', 'add_featured_image_url', 10, 3); // 10 is priority and 3 is accepted_args. Both are optional

this will give us the following in the /posts/ endpoint results

1featured_image_url: {
2	thumbnail: "https://news.mydomain.net/wp-content/uploads/images/myimage-150x150.jpg",
3	medium: "https://news.mydomain.net/wp-content/uploads/images/myimage-300x200.jpg",
4	full: "https://news.mydomain.net/wp-content/uploads/images/myimage.jpg"
5},
  • $data here is the entire default JSON response
  • the wp_get_attachment_image_src function gets the URL of any attachment image by taking its ID. Accepts any valid image size (e.g. ‘original’, ’thumbnail’ 150x150, ‘medium’ 300x200, ‘full’ etc.). The first item in the returned array is the URL of the attachment image src..
  • image_get_intermediate_size gets the image source URL by taking the attachment ID and the image size.
  • Standard image sizes are: thumbnail, medium, medium_large, large.

Add Comment count

 1// Add comment count to the API response
 2function add_comment_count($data, $post, $context) {
 3	$args = array(
 4		'post_id' => $post -> ID, // Limit results affiliated with this post ID. Default 0.
 5		'count' => true, // return only the count, not an array of comment objects
 6		'status' => 'approve'
 7	);
 8	$comments = get_comments( $args );
 9
10	$data -> data['comment_count'] = $comments;
11
12	return $data;
13}
14
15add_filter( 'rest_prepare_post', 'add_comment_count', 10, 3);
  • $data is the entire array of posts returned (default: 10)
  • $post is the individual post in that array
 1ID: 3347,
 2post_author: "1",
 3post_date: "2019-05-24 15:29:47",
 4post_date_gmt: "2019-05-24 15:29:47",
 5post_content: "This is post content. Blah blah blah",
 6post_excerpt: "This is the post excerpt. More blah.. ",
 7post_status: "publish",
 8comment_status: "open",
 9ping_status: "closed",
10post_password: "",
11post_name: "this-be-the-post-slug",
12to_ping: "",
13pinged: "",
14post_modified: "2019-06-18 07:21:50",
15post_modified_gmt: "2019-06-18 07:21:50",
16post_content_filtered: "",
17post_parent: 0,
18guid: "https://news.mydomain.net/p=?3347",
19menu_order: 0,
20post_type: "post",
21post_mime_type: "",
22comment_count: "8",
23filter: "raw"

Customize the excerpt

Precisely, remove the read more link as it goes to the wrong URL. Remove the continue reading link from auto generated excerpts by defining our own custom excerpt if one hasn’t been added by user

 1// Custom Excerpt
 2// Remove the continue reading link from auto generated excerpts by defining our own custom excerpt if one hasn't been added by user
 3function custom_excerpt ($data, $post, $context) {
 4
 5	// unset( $data -> data['excerpt'] ); // remove the excerpt field (if you want to overwrite the default 'excerpt' response sent by the API)
 6
 7	$content = $post -> post_content;
 8	$more = ' ... ';
 9
10	if ( ! has_excerpt($post -> ID)) {
11		// This post does not has a user defined excerpt
12		$data -> data['excerpt']['raw'] = wp_trim_words( $content, 55 , $more );
13	}
14	return $data;
15}
16
17add_filter( 'rest_prepare_post', 'custom_excerpt', 10, 3);
  • has_excerpt() takes a post ID and returns true/false depending on whether a custom user-defined excerpt was added for the post.

Troubleshooting

See values in $post

1function whothis ($data, $post, $context) {
2	$whothis = $post;
3	$data -> data['whothis'] = $whothis;
4	return $data;
5}
6add_filter( 'rest_prepare_post', 'whothis', 10, 3);