I’m trying to implement a custom JSON API upon WordPress, like /api3/get_posts
, I refer to the implementation of plugin JSON-API, but it just doesn’t work. Below is my code:
$myPluginBase = 'api3';
function my_plugin_init() {
global $wp_rewrite;
add_filter('rewrite_rules_array', 'my_plugin_rewrites');
add_action('template_redirect', 'my_plugin_template_rewrite');
$wp_rewrite->flush_rules();
}
function my_plugin_template_rewrite(){
global $myPluginBase;
if( isset( $_REQUEST[ $myPluginBase ] ) ){
echo $_REQUEST[ $myPluginBase ];
exit;
}
}
function my_plugin_activation() {
// Add the rewrite rule on activation
global $wp_rewrite;
add_filter('rewrite_rules_array', 'my_plugin_rewrites');
$wp_rewrite->flush_rules();
}
function my_plugin_deactivation() {
// Remove the rewrite rule on deactivation
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function my_plugin_rewrites($wp_rules) {
global $myPluginBase;
if (empty($base)) {
return $wp_rules;
}
$my_plugin_rules = array(
"$myPluginBase$" => "index.php?{$myPluginBase}=info",
"$myPluginBase/(.+)$" => "index.php?{$myPluginBase}=$matches[1]"
);
return array_merge($my_plugin_rules, $wp_rules);
}
// Add initialization and activation hooks
add_action('init', 'my_plugin_init');
register_activation_hook( __FILE__, 'my_plugin_activation');
register_deactivation_hook( __FILE__, 'my_plugin_deactivation');
It seems like the template_redirect
action works, as I open /api3=hello
, the server will send hello
back. But if I try to open /api3/hello
, it keeps showing me the home page.