Skip to content

Instantly share code, notes, and snippets.

@n8finch
Created August 29, 2016 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8finch/4f31b575be2f53cff91fd7f066f051d7 to your computer and use it in GitHub Desktop.
Save n8finch/4f31b575be2f53cff91fd7f066f051d7 to your computer and use it in GitHub Desktop.
custom-wp-rest-api-routes.php
//* =================================================
//* Mostly from Mor10's Lynda course
//* Add various fields to the WP REST API JSON output
//* https://www.lynda.com/WordPress-tutorials/WordPress-REST-API-WP-API-First-Look/383783-2.html
function register_new_restapi_fields() {
// Add Author Name
register_api_field( 'post',
'author_name',
array(
'get_callback' => 'get_author_name_from_restapi',
'update_callback' => null,
'schema' => null
)
);
register_api_field( 'post',
'category_name',
array(
'get_callback' => 'get_category_name_from_restapi',
'update_callback' => null,
'schema' => null
)
);
// Add Featured Image
register_api_field( 'post',
'featured_image_src',
array(
'get_callback' => 'get_image_src_from_restapi',
'update_callback' => null,
'schema' => null
)
);
}
function get_author_name_from_restapi( $object, $field_name, $request ) {
return get_the_author_meta( 'display_name' );
}
function get_category_name_from_restapi( $object, $field_name, $request ) {
$cats = [];
foreach ($object['categories'] as $cat ) {
array_push($cats, get_cat_name($cat));
}
return $cats;
}
function get_image_src_from_restapi( $object, $field_name, $request ) {
$imgArray = wp_get_attachment_image_src( get_post_thumbnail_id( $object['id'] ), 'full' );
return $imgArray[0];
}
add_action( 'rest_api_init', __NAMESPACE__ . '\register_new_restapi_fields' );
//* end Mor10's code
//* =================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment