WordPress.org

Make WordPress Core

Opened 15 months ago

Last modified 14 months ago

#44748 new feature request

Ability to register custom embeds to built-in endpoints

Reported by: k1sul1 Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: REST API Keywords: needs-patch
Focuses: rest-api Cc:
PR Number:

Description

Couldn't find any tickets related to this, probably because this page is broken (?): https://core.trac.wordpress.org/component/REST+API

There are situations where we "link" to other posts using custom fields, and would like to include said posts when querying for the post that includes said links.
Here's what I already get from the standard /wp/v2/posts/123 endpoint.

"linkedProductCards": [
  856628
]

I'd like to be able to easily fetch and embed the posts under linkedProductCards, with just one network request.

"_embedded": {
  "linkedProductCards": [
    { "id": 856642, "date": "2018-08-06T14:32:06", .. },
  ]
}

And I'd like to be able to have control over whether the embedded post also embeds, as making a separate network request to get the featured image object kinda defeats the purpose of this feature.

Change History (4)

#1 @k1sul1
15 months ago

This is one way of doing it at the moment but it doesn't feel right.

register_rest_field('post', 'linkedProductCards', [
  'get_callback' => function($post, $field_name, $request) {
    $params = $request->get_params();

    if (empty($params['_embed']) || $params['_embed'] === '0') {
      return [];
    }

    $linked = get_field('linkedProductCards', $post['id']);

    if (!$linked) {
      $linked = [];
    }

    return array_map(function($id) {
      return \NS\REST\get_post_from_api($id);
    }, $linked);
  },
  'schema' => [
    'description' => 'Array of posts, in REST API format',
    'type'        => 'array'
  ],
]);

#2 @TimothyBlynJacobs
15 months ago

Hi k1sul1,

This is supported. You can see some more information about it in the [docs](https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#adding-links-to-the-api-response).

You’ll probably want to use [rest_prepare_post filter](https://github.com/WordPress/wordpress-develop/blob/master/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php#L1617) as well.

Nested embeds are not currently supported.

#3 @k1sul1
15 months ago

Interesting. Didn't read well enough.

So if I understood correctly, I'm to use the rest_prepare_post filter to mutate the response with the add_link call. I think I'll manage.

Will nested embeds ever be supported?

#4 @mukesh27
14 months ago

  • Focuses rest-api added
Note: See TracTickets for help on using tickets.