How to addembed an author into REST data from a custom post type?

admin2025-06-06  4

We have a couple of post types which don't directly support authors. Instead, we have custom interfaces for choosing the author.

We end up with an author ID, though, so I'd like to inject that author ID into the REST data for that custom post type.

I've tried this:

add_filter( 'rest_post_dispatch', function( $results ) {
    $result->add_link( 'author', rest_url( '/wp/v2/users/42' ), array( 'embeddable' => true ) );
    return $results;
});

… but that returns the link on the entire response (e.g. a set of 10 custom posts) -- what I want to be able to do is, for each post, add a link with that post's own user ID.

Is this possible? I can't find documentation anywhere -- the best I found was this old page on Linking.

We have a couple of post types which don't directly support authors. Instead, we have custom interfaces for choosing the author.

We end up with an author ID, though, so I'd like to inject that author ID into the REST data for that custom post type.

I've tried this:

add_filter( 'rest_post_dispatch', function( $results ) {
    $result->add_link( 'author', rest_url( '/wp/v2/users/42' ), array( 'embeddable' => true ) );
    return $results;
});

… but that returns the link on the entire response (e.g. a set of 10 custom posts) -- what I want to be able to do is, for each post, add a link with that post's own user ID.

Is this possible? I can't find documentation anywhere -- the best I found was this old page on Linking.

Share Improve this question asked Nov 7, 2018 at 22:16 Nabha CosleyNabha Cosley 6883 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I found out how to grab each result and add a link. For the ananda_video_audio post type:

add_filter( 'rest_prepare_ananda_video_audio', function( $results ) {

    // These two lines are unique to our code of course
    $video = new Ananda_Video_Audio( $results->data['id'] ); 
    $authors = $video->get_author_IDs();

    foreach( $authors as $author_id ) {
        $results->add_link( 'author', rest_url( '/wp/v2/users/' . $author_id ), array( 'embeddable' => true ) );
    }

    return $results;

});

Because embeddable is set to true, the author data all gets added to _embedded as well, in the response. Works great.

Links I found helpful, in case you're doing something similar:

  • Adding links
  • List of REST filters in WordPress
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749198860a317192.html

最新回复(0)