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

2 Answers
2

This code will add categories_names field to wp rest api response:

function wpse_287931_register_categories_names_field() {

    register_rest_field( 'project',
        'categories_names',
        array(
            'get_callback'    => 'wpse_287931_get_categories_names',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

add_action( 'rest_api_init', 'wpse_287931_register_categories_names_field' );

function wpse_287931_get_categories_names( $object, $field_name, $request ) {

    $formatted_categories = array();

    $categories = get_the_category( $object['id'] );

    foreach ($categories as $category) {
        $formatted_categories[] = $category->name;
    }

    return $formatted_categories;
}

Leave a Reply

Your email address will not be published. Required fields are marked *