Rewrite rule for admin-ajax.php

There are a few things to sort out here.

The first is why your rewrite rule will not work.

add_rewrite_rule('/api', '/wp-admin/admin-ajax.php', 'top');

The WordPress rewrite does not redirect to a page. What does is it parses the path using regular expressions into a WordPress query vars. If you disable pretty URLs in WordPress, you’ll see the query vars in the URL for pages on your site: http://example.com/?p=262, http://example.com/?page_id=2, or http://example.com/?m=201309`.

After the rewrite rules create query vars, WordPress then calls the content from the database and sets the flags (is_single(), is_404(), etc). Then the appropriate template is found based upon those flags.

Your rewrite rule will not work as it generates no query vars. WordPress doesn’t call the file for it.

What can you do instead?

  1. In you .htaccess file, add a server rewrite rule to map /api to /wp-admin/admin-ajax.php.
  2. Just call /wp-admin/admin-ajax.php instead.
  3. Add your own ajax handler by hooking into the template_redirect hook.

Leave a Comment