Get the Category Name instead of ID from WP-API

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 Comment