I’m in the process of converting my existing WordPress site to use Preact/Redux on the frontend and use the WP REST API to get post data back from the admin.

I’ll be using React Router and a rewrite in .htaccess to rewrite the URLs to the index.html file, and React Router should handle the requests.

Given an existing URL of https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/ I assume I’ll setup my route as /:year/:month/:slug

My question is, how would I use those params to get the post ID so I can call the REST endpoint for: GET /wp/v2/posts/<id>?

Perhaps there is another way to achieve this? I tried several combinations of:
https://peteschuster.com/wp/v2/posts/2017/10/high-praise-react-react-ecosystem/ to no avail. I was thinking it might be possible similar to how /feed is handled like:
https://peteschuster.com/2017/10/high-praise-react-react-ecosystem/json

Any guidance would be greatly appreciated. Thanks!

3 Answers
3

The core rewrite API does offer the function url_to_postid() (as mentioned by @stephen-sabatini) which can find a post ID from a URL. However it seems less than ideal to have to make a request up front just to determine the post ID…

The REST API does not natively offer the ability to query by date beyond setting before and after args so that won’t be of much help to you.

You could potentially ignore the date params and query by slug. For example:

https://peteschuster.com/wp-json/wp/v2/posts?slug=high-praise-react-react-ecosystem

Alternatively, you could make a custom endpoint and perform whatever type of query you want. Check the REST API handbook for more information.

On the idea of a /json endpoint: This isn’t something that exists natively, but it is certainly doable.

To implement it, have a look at rewrite endpoints:

  • Codex page
  • Code reference page
  • Blog post with more info on using rewrite endpoints

Keep in mind that this would be completely separate from the REST API, however you could probably reuse the REST API internally with something like:

$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$request->set_param( 'slug', 'high-praise-react-react-ecosystem' );
$response = rest_do_request( $request );
$post = $response->data;

Using the REST API in this way is briefly touched on in the handbook FAQ.

This would add some extra complexity to your server config, as now you would have to route requests ending in json straight to WordPress instead of your frontend, but that shouldn’t be too difficult.

Hopefully that gives you some ideas…

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *