Query WP REST API Using Any Permalink URL

Problem

I’d started the journey of creating a fully async WordPress site using WP REST API at The Symphony Agency.  For interacting with posts and listing out a blog, the API seemed great.  However, I quickly ran into the issue of not being able to do URL based queries on any page, post or post type.  For an Asynchronous WordPress site to be able to cover all the bases, it needs to be able to take advantage of the WordPress permalink system, as well as provide front end linkages to all systems that would typically be available when writing templates in PHP.

I’d built a routing system that would send any request URL (from root) through the WP REST API to WordPress, and I needed WordPress to respond with enough of the query to give me information to determine:

  • Post type
  • Template
  • archive or single
  • 404
  • search
  • page
  • etc

Solution

After endless searching and hair pulling I came up with this extension to the WP REST API.

function route_handler($request)
{
    global $wp;
    global $wp_query;
    $parameters = $request->get_json_params();
    $url = $parameters["url"];
    $_SERVER['REQUEST_URI'] = $url;
    $wp->parse_request();
    $wp->query_posts();
    //Insert queries for more specific information
    //Modify or simplify the query results
    //Here I'm just returning the query results.
    return json_encode($wp_query);
}
add_action('rest_api_init', function () {
    register_rest_route('custom-theme/v1', '/route', array(
        'methods' => 'POST',
        'callback' => 'route_handler',
    ));
});

This method allows me to sent an asynchronous request via JSON with “url” as a key value pair, and have WordPress return the results as JSON.  With this, you simply need to send any url request for content, get the content, set the page’s url, and display it.  Other internal clicks to anchor tags should be built to send async requests through this method, using the default WordPress permalink structure.

Hope this helps!


Also published on Medium.

Leave a Reply

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