[API] Registering A Custom Taxonomy With REST API Support [ok]

Previous[API] Registering A Custom Post Type With REST API Support full (ok)Next[API] Adding REST API Support To Existing Content Types [ok]
Last updated

Last updated
/**
* Register a genre post type, with REST API support
*
* Based on example at: https://codex.wordpress.org/Function_Reference/register_taxonomy
*/
add_action('init', 'my_book_taxonomy', 30);
function my_book_taxonomy() {
$labels = array(
'name' => _x('Genres', 'taxonomy general name'),
'singular_name' => _x('Genre', 'taxonomy singular name'),
'search_items' => __('Search Genres'),
'all_items' => __('All Genres'),
'parent_item' => __('Parent Genre'),
'parent_item_colon' => __('Parent Genre:'),
'edit_item' => __('Edit Genre'),
'update_item' => __('Update Genre'),
'add_new_item' => __('Add New Genre'),
'new_item_name' => __('New Genre Name'),
'menu_name' => __('Genre'),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'genre'),
'show_in_rest' => true,
'rest_base' => 'genre',
'rest_controller_class' => 'WP_REST_Terms_Controller',
);
register_taxonomy('genre', array('book'), $args);
}
function my_plugin_rest_route_for_term($route, $term) {
if ($term->taxonomy === 'genre') {
$route = '/wp/v2/genre/' . $term->term_id;
}
return $route;
}
add_filter('rest_route_for_term', 'my_plugin_rest_route_for_term', 10, 2);