For my own sanity I\'m trying to create a route for an ajax api that looks something like:
/api/
I\'d like wordpress to handle th
Seems like you are looking for wordpress json-api plugin,which is one of the nicely built plugins I have used,also very easily extendable.Good luck.
You have to use add_rewrite_rule
Something like:
add_action('init', 'theme_functionality_urls');
function theme_functionality_urls() {
/* Order section by fb likes */
add_rewrite_rule(
'^tus-fotos/mas-votadas/page/(\d)?',
'index.php?post_type=usercontent&orderby=fb_likes&paged=$matches[1]',
'top'
);
add_rewrite_rule(
'^tus-fotos/mas-votadas?',
'index.php?post_type=usercontent&orderby=fb_likes',
'top'
);
}
This creates /tus-fotos/mas-votadas
and /tus-fotos/mas-votadas/page/{number}
, that changes the orderby query var for a custom one, which I handle in the pre_get_posts filter.
New variables can also be added using the query_vars
filters and adding it to the rewrite rule.
add_filter('query_vars', 'custom_query_vars');
add_action('init', 'theme_functionality_urls');
function custom_query_vars($vars){
$vars[] = 'api_action';
return $vars;
}
function theme_functionality_urls() {
add_rewrite_rule(
'^api/(\w)?',
'index.php?api_action=$matches[1]',
'top'
);
}
Then, handle the custom request:
add_action('parse_request', 'custom_requests');
function custom_requests ( $wp ) {
$valid_actions = array('action1', 'action2');
if(
!empty($wp->query_vars['api_action']) &&
in_array($wp->query_vars['api_action'], $valid_actions)
) {
// do something here
}
}
Just remember to flush the rewrite rules by visiting /wp-admin/options-permalink.php
or calling flush_rewrite_rules only when needed, since it's not a trivial process.