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

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


Published at - Aug 13, 2021

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;
}




About author

Harendra
Harendra Kanojiya

Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.



Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile