I’m attempting to using WP REST API on a site that uses pretty URLs, not ID’s (which is typical in a REST scenario). All I have to query with is the requested URL.
Lets say a user lands on example.com/about
, I can do the following:
/wp-json/wp/v2/pages/?slug=about
No sweat. However, what if a users lands on example.com/about/team
? I could query by the slug team
, but maybe my site also has example.com/contact/team
as a possible URL. It’s not reliable.
What I need is a way of achieving the following:
/wp-json/wp/v2/pages/?permalink=about%2team
It’s unfeasible to have to set up custom routes for each page that gets created. I’m surprised the API doesn’t appear to have some kind of permalink handler out of the box.
Well, since there is no tool to handle all of the cases, you have to be a bit crafty. It is possible to use a combination of wp functions like
url_to_postid
orget_term_by
and global variables like$wp_taxonomies
to figure out all of the cases.You can create a custom endpoint and use the code below to handle the path. I think that I have covered all of the possible cases, but use carefully cause I might miss something.