I went through a lot of posts and googled a lot, but still couldn’t get this to work. I’m trying to create a rewrite rule for admin-ajax.php, to achieve the same results shown here:
Adding admin-ajax.php to the frontend. Good or bad idea?
However, I don’t want to use htaccess file. Instead, I need this to work by dynamically adding a rule (like using add_rewrite_rule), for instance, because the ajax function to be called lies inside a plugin I’m writing and I want to provide a friendly URL to be called.
I seem to have followed all best practices regarding that approach. I hooked the rule flush on activation and deactivation hooks of my plugin. Also did the route adding on the init action:
add_rewrite_rule('/api', '/wp-admin/admin-ajax.php', 'top');
All I get are 404’s, though.
Edit: this is how I’m doing right now:
// rewrite rules and API hooks
add_action('init', array('MYCLASS', 'add_custom_rules'), 1);
add_filter('query_vars', array('MYCLASS', 'add_custom_query_vars'), 1, 1);
add_action('parse_request', array('MYCLASS', 'add_custom_parse_request'), 1, 1);
On add_custom_rules, I do:
add_rewrite_rule('my-api.php$', 'index.php?my-api=1', 'top');
On add_custom_query_vars, I do:
$query_vars[] = 'my-api';
return $query_vars;
On add_custom_parse_request, I do:
if (array_key_exists('my-api', $wp->query_vars)) {
$action = $wp->query_vars['action'];
$API = new myAPI();
$API->{$action}();
exit();
}
What am I still missing? Thanks again.
There are a few things to sort out here.
The first is why your rewrite rule will not work.
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?
.htaccess
file, add a server rewrite rule to map/api
to/wp-admin/admin-ajax.php
./wp-admin/admin-ajax.php
instead.template_redirect
hook.