简体   繁体   中英

How do I retrieve a list of posts based on a tag slug in WP Rest API V2?

I have an application that retrieves data from a Wordpress site using the WP Rest API V2. The API has recently been change from using a 'filter[tag]=' to a new syntax. I am looking to retrieve a list of posts within a specific tag.

Old syntax:

http://demo.wp-api.org/wp-json/wp/v2/posts?filter[tag]=slug

The new syntax looks like this:

http://demo.wp-api.org/wp-json/wp/v2/posts?tags=id

It now takes an ID integer instead of a slug as argument. I have looked over the documentation but I can't seem to find a solution for this. I have no option of using the id, I can only use the slug!

The WP Rest API documentation can be found here: https://developer.wordpress.org/rest-api/reference/posts/

Do you have any idea how to solve this?

Just get the list of tags by calling http://demo.wp-api.org/wp-json/wp/v2/tags before your requesting posts on a specifiy tagId. In that way you will find the tagId you need by filtering the data by your "slug". The demo API is not support CORS thats way I dont create a working fiddle.

Nested $http request bad example

 $http({
    method: 'GET',
    url: 'http://demo.wp-api.org/wp-json/wp/v2/tags'   
 }).then(function (result) {

      var filtered = filterFilter(result.data, { slug: 'dolor'});

      $http({
        method: 'GET',
        url: 'http://demo.wp-api.org/wp-json/wp/v2/posts?tags=' + filtered[0].id
     }).then(function (result) {
          console.log(result.data);
     });
 });

Looking at the official API docs for TAGS , you can search for strings in the tags schema with a request like this:

http://demo.wp-api.org/wp-json/wp/v2/tags?search=yourslug

The resulting JSON output will display tags containing the string you searched in any of the schema fields, like slug .

After you retrieved the desired tag, you can fetch the posts with that specific tag using it's ID (as suggested by @lin).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM