How to get WordPress rest api post with category and tag name ?

February 17, 2021
28
Views

To get post with category name and tags name we need to add following code into functions.php file.

Please copy and paste this code at the bottom of the page –

function add_category_info_in_post() {
    register_rest_field(
        array('post'),
        'categories_info',
            array(
                'get_callback' => 'get_category_info_for_post',
                'update_callback' => null,
                'schema' => null,
            )
    );
}
add_action('rest_api_init', 'add_category_info_in_post');

function get_category_info_for_post($object, $field_name, $request) {
    $formatted_categories = array();
    $categories = get_the_category($object['id']);
    foreach ($categories as $category) {
        $formatted_categories[] = ['name' => $category->name,'slug' => $category->slug];
    }
    return $formatted_categories;
}

function add_tag_info_in_post(){
    register_rest_field(
        array('post'),
            'tags_info',
            array(
                'get_callback' => 'get_tag_info_for_post',
                'update_callback' => null,
                'schema' => null,
        )
    );
}
add_action('rest_api_init', 'add_tag_info_in_post');

function get_tag_info_for_post($object, $field_name, $request){
    $formatted_tags = array();
    $tags = get_the_tags($object['id']);
    foreach ($tags as $tag) {
        $formatted_tags[] = ['name' => $tag->name,'slug' => $tag->slug];
    }
    return $formatted_tags;
}

Article Tags:
· ·
Article Categories:
Php

Comments are closed.