Skip to content

Instantly share code, notes, and snippets.

@joehoyle
Created October 27, 2015 22:07
Show Gist options
  • Save joehoyle/12e37c293adf2bb0ea1b to your computer and use it in GitHub Desktop.
Save joehoyle/12e37c293adf2bb0ea1b to your computer and use it in GitHub Desktop.
<?php
/**
* Whitelist embedded links in the REST API responses
*
* This is often useful if you want to only get specified resources embedded along with the
* main resources, rather than the "all of nothing" approach of passing `?_embed` to the API request.
*
* You can either pass a comma seperated list of relationships or an array of string via the `_embed_include` query param.
*
* For example, `curl example.com/wp/v2/posts/18?_embed_include=author,replies`
*/
add_filter( 'rest_pre_serve_request', function( $served, WP_REST_Response $response, WP_REST_Request $request, WP_REST_Server $server ) {
$data = $response->get_data();
$links = $response->get_links();
if ( empty( $_GET['_embed_include'] ) || ! $links ) {
return $served;
}
$include = is_array( $_GET['_embed_include'] ) ? $_GET['_embed_include'] : explode( ',', $_GET['_embed_include'] );
foreach ( $links as $rel => $links ) {
if ( ! in_array( $rel, $include ) ) {
foreach ( $links as $link ) {
if ( ! empty( $link['attributes']['embeddable'] ) ) {
$response->remove_link( $rel, $link['href'] );
$attributes = $link['attributes'];
unset( $attributes['embeddable'] );
$response->add_link( $rel, $link['href'], $attributes );
}
}
}
}
$_GET['_embed'] = true; // nasty hack to spoof the rest api into embedding
return $served;
}, 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment