wp-api-meta-endpoints icon indicating copy to clipboard operation
wp-api-meta-endpoints copied to clipboard

Meta _links do not appear post-beta13

Open duncanjbrown opened this issue 8 years ago • 1 comments

This PR https://github.com/WP-API/WP-API/commit/32e1940989fa8b53b2044b9a088df66ccb44589e removed meta links from Post controller responses in the WP-API plugin. This plugin doesn’t add them back in, though, so they're gone everywhere. I looked for a filter to remedy this, but couldn’t find one. Happy to implement any suggestions in a PR 😄

duncanjbrown avatar Apr 18 '16 18:04 duncanjbrown

In case anyone else is having this problem, here's some code to restore the meta links for posts.

Note that the namespace is hardcoded because we're no longer in the context of REST_Posts_Controller, so can't read its properties.

add_action( 'rest_api_init', function() {
    $post_types = get_post_types( array( 'public' => true ), 'names' );

    foreach( $post_types as $post_type ) {
        if ( post_type_supports( $post_type, 'custom-fields' ) ) {
            add_filter( "rest_prepare_${post_type}", 'prepare_meta_link_for_post_type' , 10, 3);
        }
    }

    function prepare_meta_link_for_post_type( $response, $post, $request ) {
        $post_type = get_post_type_object( $post->post_type );
        $rest_base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name;
        $base = sprintf( '/wp/v2/%s/', $rest_base );
        $response->add_link(
            'https://api.w.org/meta',
            rest_url( $base . $post->ID . '/meta' ),
            array( 'embeddable' => true )
        );
        return $response;
    }
});

duncanjbrown avatar Jul 22 '16 15:07 duncanjbrown