-
-
Save rheinardkorf/b97568a11b77340a7424f97350d33e23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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