3
votes

Trying to get post tags with wordpress API - api call is /wp-json/wp/v2/posts

ourHTMLString += '<i class="fa fa-tags">"' + postsData[i].tags + '"</i>';

It is returning these values

"tags": [
        766,
        19,
        578
],

I need the tag name and href to this, not sure how to get this. I have tried postsData[i].wp:term[i].tag.name - cannot find a solution. Any help? thanks

3

3 Answers

6
votes

I think you need to do another request to get this and use include to list only theses tags. eg: /wp-json/wp/v2/tags?include=766,19,578

https://developer.wordpress.org/rest-api/reference/tags/

1
votes

Send a request to the Wordpress site with the tag's id:

http://demo.wp-api.org/wp-json/wp/v2/tags/TagID

REF : https://developer.wordpress.org/rest-api/reference/tags/#definition

Definition

GET /wp/v2/tags/

Example Request

$ curl http://demo.wp-api.org/wp-json/wp/v2/tags/

0
votes

If we need tags in same API call we can add a custom field in our response.

we can add following code in theme's function.php file

add_action('rest_api_init', 'bs_rest_api_hooks');
function bs_rest_api_hooks() {
    register_rest_field(
        'post',
        'mtags',
        array(
            'get_callback' => 'm_get_tags',
        )
    );
}
function m_get_tags($object, $field_name, $request) {

    $tags = get_the_tags($object["id"]);

    return $tags;
}