Created
July 7, 2020 14:31
Add element to rest end point.
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 | |
/** | |
* 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