Wordpress重写机制以不同的方式工作,不像。htaccess重写规则。有关它的更多信息,请访问codex (Rewrite API, WP_Rewrite, 等等)。但快速解决方法可能是:
首先,我们需要注册查询变量并重写规则:
function myplugin_add_query_var( $vars ) {
$vars[] = \'myplugin_api\';
return $vars;
}
add_filter( \'query_vars\', \'myplugin_add_query_var\' );
function myplugin_update_rewrite_rules( $rules ) {
$newrules = array();
$newrules[\'api\\/endpoint\\.php$\'] = \'index.php?pagename=api&myplugin_api=1\';
return $newrules + $rules;
}
add_filter( \'rewrite_rules_array\', \'myplugin_update_rewrite_rules\' );
要完成重写规则的注册,我们需要刷新插件激活/停用的规则:
function myplugin_activate() {
flush_rewrite_rules();
}
register_activation_hook( __FILE__, \'myplugin_activate\' );
function myplugin_deactivate() {
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, \'myplugin_deactivate\' );
使重写规则正常工作的一种魔法:D
function myplugin_a_piece_of_magic_on_init() {
global $wp_rewrite;
$wp_rewrite->use_verbose_page_rules = !preg_match( "/api\\/endpoint\\.php$/i", $_SERVER[\'REQUEST_URI\'] );
}
add_action( \'init\', \'myplugin_a_piece_of_magic_on_init\' );
最后检查我们的查询var是否显示在wp操作上:
function myplugin_check_query_var( $wp ) {
if ( array_key_exists( \'myplugin_api\', $wp->query_vars ) ) {
// do api stuff here ...
exit;
}
}
add_action( \'wp\', \'myplugin_check_query_var\' );