Skip to content

Instantly share code, notes, and snippets.

@marcelo-ribeiro
Last active October 10, 2017 22:03
Show Gist options
  • Save marcelo-ribeiro/9c9614e0de82487dbdd108e6f2a8b759 to your computer and use it in GitHub Desktop.
Save marcelo-ribeiro/9c9614e0de82487dbdd108e6f2a8b759 to your computer and use it in GitHub Desktop.
WP REST API - SNIPPETS
// Access-Control-Allow-Origin
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
$origin = get_http_origin();
if ( $origin && in_array( $origin, array(
'http://localhost'
) ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
}
return $value;
});
}, 15 );
// REST API - register and set parent category
add_action( 'rest_api_init', 'register_parent_category' );
function register_parent_category() {
register_rest_field( 'post',
'parent_category',
array(
'get_callback' => 'set_parent_category',
'update_callback' => null,
'schema' => null,
)
);
}
function set_parent_category( $object, $field_name, $request ) {
if ( empty( $object['categories'] ) ) return false;
foreach ( $object['categories'] as $key => $category ) {
$parentCategory = get_ancestors( $category, 'category' );
if ( !empty ( $parentCategory ) ) {
return get_term( reset( $parentCategory ), 'category' );
}
else {
return get_term( $category, 'category' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment