34

It works for my pages but not for my posts. If I go to example.com/wp-json/wp/v2/pages?slug=page-name it will retrieve the page correctly. If I go to example.com/wp-json/wp/v2/posts?slug=post-name it will not retrieve a post in the same way. Can someone tell me how to get a post by slug name? The post does have a category too, but I don't know if it's necessary or how to properly add that to the query. All the documentation I have found refers to the [filter] function which is no longer supported.

3
  • 1
    I'm passed sitename.com/wp-json/wp/v2/posts?slug=post-slug, its works Feb 22, 2017 at 14:02
  • 1
    Try the post slug instead of post name Feb 22, 2017 at 14:02
  • I've discovered that there might be an issue with my Paid Memberships Pro plugin. Any posts that is considered restricted content is not able to be called by its slug and returns nothing instead of "Page is restricted, please login."
    – Alex
    Feb 22, 2017 at 21:02

2 Answers 2

67

Posts: sitename.com/wp-json/wp/v2/posts?slug=post-slug

Pages: sitename.com/wp-json/wp/v2/pages?slug=page-slug

Custom post type: sitename.com/wp-json/wp/v2/POST_TYPE?slug=post-slug

1
0

Rather than hardcoding the api root it is safer to get it like that:

$api_root = trailingslashit( get_home_url() ) . rest_get_url_prefix();

and then

Posts: $api_root . '/wp/v2/posts?slug={slug}';

Pages: $api_root . '/wp/v2/pages?slug={slug}';

Custom post type: $api_root . '/wp/v2/{post_type}?slug={slug}';

Reference

https://developer.wordpress.org/reference/functions/rest_get_url_prefix/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.