Created
August 29, 2016 15:44
-
-
Save n8finch/4f31b575be2f53cff91fd7f066f051d7 to your computer and use it in GitHub Desktop.
custom-wp-rest-api-routes.php
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
//* ================================================= | |
//* 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