Using the HTML5 History API (History.pushState()) with WordPress

In order to take advantage of HTML5’s History API, the application must ignore the URI in the http request and resolve to the root – otherwise you’ll get a 404 error. This can be an issue with a WordPress application because WordPress uses a similar technique by using either Apache or NGINX to resolve all requests to index.php, which then parses the URI and renders the corresponding page/post/archive/ect.

The solution is to set a programmatic rewrite within the WordPress application rather than dealing with it on the web server level. To do this we make use of the add_rewrite_rule() method in WP.

  • $slug = 'myapp';  This should be the unqiue slug your application uses. For example, for “myapp”, URI’s in the application would look like:
    • /myapp/easy/as/123/abc
    • /myapp/do/re/mi
    • /myapp/baby/you/and/me
  • $id = get_option('page_on_front');  In our case, the application was the front page, but this could be any ID that the web app using push state lives on.