Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
# Source: https://gist.github.com/joehoyle/12e37c293adf2bb0ea1b
/**
* 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 );
function prepare_whitelist_embed( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) {
$data = $response->get_data();
$links = $response->get_links();
if ( empty( $_GET['_embed_include'] ) || ! $links ) {
return $response;
}
$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 $response;
}
add_filter( 'rest_prepare_post', 'prepare_whitelist_embed', 10, 3 );
add_filter( 'rest_prepare_page', 'prepare_whitelist_embed', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.