WP Rest API get page from path


I am looking to use the rest API to use WordPress as a headless CMS, but I am curious as to how best to get a page using the path.

Example, if WordPress is hosted at cms.example.com and my frontend is at example.com. If I create a page at cms.example.com/services/service-a I would want it accessible on the frontend at example.com/services/service-a. If my front end takes ‘services/service-a’ how can I find the right page?

My first thought was using the slug, until I realized the slug only matches the last part. In this example the slug would be ‘service-a’ not ‘serviceservice-a’. I can specify a slug and a parent ID but this would require a a call for each level or hierarchy to work up the tree to get the parent id.

I have also briefly considered ignoring all previous levels of hierarchy and just looking at the last part of the path to use the slug, but I am not sure if that would have any unintended consequences.

I was thinking to setup a custom endpoint to take the path, run it through the get_page_by_path() function then return the id. But that means each page load would require 2 API calls, or at least each page load that isn’t at the first level of hierarchy.

But wanting to limit each request to a single API call I am thinking either if possible add a custom argument to the pages API endpoint to specify a full path to search by for the response, or else if that is not explicitly possible creating my own endpoint to accept the path argument then return the matching page object. Obviously in this case my preference would be for the former over the latter as that should require less work for a plugin and make the most out of the existing code in WordPress.

Is it possible to add a custom option to an existing endpoint? Is there a better method to do this with a single API call?

user3452 3 years 2020-06-05T21:10:23-05:00 0 Answers 66 views 0

Leave an answer