I'm trying to get the category name instead of the ID from the WP REST API for my Custom Post Type. Some articles about endpoint modification gave me some ideas on how to solve it, but unfortunately i'm not getting it to work. This is my Code (* removed irrelevant code at some lines):
CUSTOM POST TYPE
<?php
add_action( 'init', 'portfolio_projects' );
function portfolio_projects() {
$labels = array([...]);
$args = array(
[...]
'show_in_rest' => true,
'rest_base' => 'projects',
'rest_controller_class' => 'Category_Data',
'supports' => array( 'title', 'thumbnail', 'editor'),
'taxonomies' => array('post_tag', 'category')
);
register_post_type( 'project', $args );
}
CONTROLLER CLASS
<?php
/**
* Category data
*/
class Category_Data extends WP_REST_Posts_Controller
{
public function init()
{
add_action('rest_api_init', array(
$this,
'add_category_data'
));
}
/**
* Add the category data
*/
public function add_category_data()
{
register_rest_field('project', 'category_data', ['get_callback' => array(
$this,
'get_all_category_data'
) , ]);
}
/**
* Get all the category data
*
* @param $object
* @param $field_name
* @param $request
*
* @return array
*/
public function get_all_category_data($object, $field_name, $request)
{
return get_the_category($object['id']);
}
}
I'd love to hear your ideas and thoughts on this. Thanks
functions.php