I am using the WP REST API to return data from a custom post that has a custom taxonomy. This is my code -
add_action( 'rest_api_init', 'register_book_type' );
function register_book_type() {
register_rest_field( 'lesson',
'book_type',
array(
'get_callback' => 'get_book_type',
'update_callback' => null,
'schema' => null,
)
);
}
function get_book_type( $object, $field_name, $request ) {
$name = [];
$object = get_terms(array(
'taxonomy' => 'book_type'
));
foreach ($object as $term) :
array_push($name, $term->name.' ');
endforeach;
return implode('/ ', $name);
}
This returns all the taxonomy names, but I need it to return only the taxonomy names that apply to the specific post.
How can I change this so it only displays taxonomy names for the specific post?
My Answer:
> 'get_book_type',_ )_ );_}_function get_book_type( $object, $field_name, $request ) {_ $terms = get_the_terms( $object['id'], 'book_type' );_ if ( !empty( $terms ) ) {_ $term = array_shift( $terms );_ return $term->name;_ } else {_ return '';_ }_}_This code registers a custom field 'book_type' for the custom post type 'lesson' and defines a callback function 'get_book_type' to retrieve the custom taxonomy term name for the post. The function uses the 'get_the_terms' function to get the terms associated with the post ID and returns the name of the first term found. If no terms are found, it returns an empty string.
Rate this post
5 of 5 based on 2744 votesComments