简体   繁体   中英

How to access /posts WordPress JSON REST API and filter by post_type?

I have a number of posts in the table wp_3_posts with the post_type "people". This post_type is created using the Admin Columns plugin.

How do I retrieve these?

The documentation for Posts offers filtering by categories or tags but post_type is neither of these.

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

Thank you:]

If I got your question the right way, you want to get posts of a custom post type with REST API.

You have to set show_in_rest and public in the arguments when you create the custom post type in wordpress.

add_action( 'init', 'my_cpt' );
function my_cpt() {
    $args = array(
      'public'       => true,
      'show_in_rest' => true,
      'label'        => 'My Custom Post'
    );
    register_post_type( 'mycustompost', $args );
}

More about this: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/

With that having set, you can get the posts of post type with using the right parameters in the url.

So if you just want to get posts, you can use:

https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10

I would suggest setting the per_page to have control if you are getting a lot of posts.

You can also have access to more data without additional HTTP requests using _embed

https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10&_embed=wp:term,wp:featuredmedia

For example, with this you get taxonomy terms and urls of different featured image sizes.


So you do not need to get all posts (and post types) of your website and then filter by post type, but just get posts of this post type instead. You can than do more filtering using global parameters:

https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/

With VueJS (in my opinion better performance) this would look something like:

fetch("https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10")
        .then(response => response.json())
        .then((data => {
            this.mycustompost = data;
        }))

Or if using standard javascript something like:

let state = {
      posts: [],
      baseUrl: 'https://yoursite.com/wp-json/wp/v2/mycustompost',
      perPage: '?per_page=10',
      wpFetchHeaders: {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Expose-Headers': 'x-wp-total'
        }
      }
    }

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