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.
.htaccess
rule.