Skip to content

Instantly share code, notes, and snippets.

@jomurgel
Created July 7, 2020 14:31
Show Gist options
  • Save jomurgel/f25c8da7abfc14a6ee9e7202503b4c88 to your computer and use it in GitHub Desktop.
Save jomurgel/f25c8da7abfc14a6ee9e7202503b4c88 to your computer and use it in GitHub Desktop.
Add element to rest end point.
<?php
/**
* Adds category names field to faqs post type.
*/
function add_category_names_to_api() {
register_rest_field(
'post', // post type.
'category_names', // element.
[
'get_callback' => __NAMESPACE__ . '\return_category_names'
]
);
}
add_action( 'rest_api_init', __NAMESPACE__ . '\add_category_names_to_api' );
/**
* Populate post category names for reference.
*
* @param array $response Array of response properties so far.
*
* @return string list of comma-separated category names.
*/
function return_category_names( $response ) {
global $post;
// Shouldn't need this, but only make this update for posts.
if ( 'post' !== $post->post_type ) {
return '';
}
// Get terms.
$category_list = [];
$terms = get_the_terms( $post, 'category' );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return '';
}
foreach( $terms as $term ) {
$category_list[] = $term->name;
}
return implode( ', ', $category_list );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment