Developers: YARPP REST API for Related Posts

IN THIS ARTICLE

YARPP adds a REST API endpoint for fetching related posts. The most current version mostly uses your saved YARPP settings.

The JSON results from the REST API query will be for the same posts as you would see visiting a post on your website (the same quantity and order). It is possible to override the quantity at the time of making the REST API request.

The YARPP REST API emulates the WP REST API, so it's a good idea to first be familiar with the WP REST API Handbook.

Schema

The schema, or shape of the response, exactly matches the WordPress core Posts route's schema. The only differences are:

  • There is an extra score property, showing how related the reference post is to the related post.
  • YARPP's endpoint will return different posts, based on what YARPP's relatedness criteria and other settings.
GET /wp-json/yarpp/v1/related/{id}
curl https://example.com/wp-json/yarpp/v1/related/1
limit

Override's YARPP setting's "Maximum number of related posts." The maximum number is 20.

Default: YARPP setting's "Maximum number of related posts."

context

Scope under which the request is made; determines fields present in the response.

Default: embed different from WordPress' default! We default to embed, which excludes the often-unnecessary post's body, whereas WordPress core endpoints default to view.

One of: view, embed, edit

password Pass in the post's password if you want to see related posts on a password-protected post.

Note: You can, of course, also pass in the WP REST API's Global Parameters like _fields, _embed, _method and _envelope.

  1. Get related posts, including their post content
    curl https://example.com/wp-json/yarpp/v1/related/1?context=view
  2. Get more related posts (limit)
    curl https://example.com/wp-json/yarpp/v1/related/1?limit=20
  3. Only get post's ID, title, and permalink
    curl https://example.com/wp-json/yarpp/v1/related/1?_fields=id,title,link
  4. Get posts related to a password-protected post
    curl https://example.com/wp-json/yarpp/v1/related/1?password=the_password_i_set_on_the_post
  5. Get related posts with their authors and categories
    curl https://example.com/wp-json/yarpp/v1/related/1?_embed=1

    While you can explore the JSON entities returned yourself, here's where to find some common data:

    Post Title
    response[0]['title']['rendered']
    Author Name
    response[0]['_embedded']['author'][0]['name']
    Author Link
    response[0]['_embedded']['author'][0]['link']
    Post Link
    response[0]['link']
    Thumbnail URL
    response[0]['_embedded']['wp:featuredmedia'][0]['source_url']
    Post Excerpt
    response[0]['excerpt']['rendered']
    (note: if the excerpt was not explicitly set on the post, the WP REST API automatically sets an excerpt based on the post content)
    Published Date Local Time:
    response[0]['date']
    UTC Time:
    response[0]['date_gmt']
    Modified Date Local Time:
    response[0]['modified']
    UTC Time:
    response[0]['modified_gmt']
    Tags and Category Names
    response[0]['_embedded']['wp:term'][0]['name']
    YARPP Score
    response[0]['score']
     

Optimizing

To speed up any WP REST API responses, including YARPP's REST API, you can use a plugin like WP REST Cache. Just activate it and YARPP's routes will get served from cache stored by that plugin. From internal testing, we found this reduced load time to 70% or 50%.

For further optimization, you can instruct the client browser to cache the results internally too. To do so, add this code snippet to your theme:

add_filter(
	'rest_post_dispatch',
	function(WP_REST_Response $rest_response, WP_REST_Server $server, WP_REST_Request $request){
		if(strpos($request->get_route(), '/yarpp/v1/related') === 0){
			$seconds_to_cache = 604800; // 1 week
			$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
			$rest_response->header("Expires", $ts);
			$rest_response->header("Cache-Control", "public, max-age=$seconds_to_cache");
		}
		return $rest_response;
	},
	10,
	3
);

That will cause the YARPP REST API responses to get cached for a week in the browser, which can reduce load time, but you will sometimes be serving stale content.

Extending

Because YARPP's REST API route wraps the WordPress REST API, any custom fields added to post entities via register_rest_field will also appear in YARPP responses.

For example, this code snippet adds a field named "slug_field" to all post entities returned from the WP REST API (eg wp-json/wp/v2/posts) and YARPP's endpoint (eg wp-json/yarpp/v1/related/123.)

function slug_add_post_data() {
	register_rest_field('post',
		'slug_field',
		array(
			'get_callback' => 'slug_get_field',
			'update_callback' => 'slug_update_field',
			'schema' => array(
				'description' => 'My special field',
				'type' => 'string',
				'context' => array('view', 'edit')
			)
		)
	);
}

add_action('rest_api_init', 'slug_add_post_data');

function slug_get_field($post, $field_name, $request) {
	return get_post_meta($post->id, $field_name);
}

function slug_update_field($value, $post, $field_name) {
	if (!$value || !is_string($value)) {
		return;
	}

	return update_post_meta($post->ID, $field_name, strip_tags($value));
}
Was this article helpful?
6 out of 10 found this helpful