WordPress中有两种类型的重写规则:内部规则(存储在数据库中,由WP::parse_request()), 和外部规则(存储在.htaccess
并由Apache解析)。您可以选择任何一种方式,这取决于您在所调用的文件中需要多少WordPress。
External Rules:
外部规则最容易设置和遵循。它将执行
my-api.php
在插件目录中,无需从WordPress加载任何内容。
add_action( \'init\', \'wpse9870_init_external\' );
function wpse9870_init_external()
{
global $wp_rewrite;
$plugin_url = plugins_url( \'my-api.php\', __FILE__ );
$plugin_url = substr( $plugin_url, strlen( home_url() ) + 1 );
// The pattern is prefixed with \'^\'
// The substitution is prefixed with the "home root", at least a \'/\'
// This is equivalent to appending it to `non_wp_rules`
$wp_rewrite->add_external_rule( \'my-api.php$\', $plugin_url );
}
Internal Rules:
内部规则需要做更多的工作:首先,我们添加一个重写规则,添加一个查询变量,然后我们将此查询变量公开,然后我们需要检查此查询变量是否存在,以将控件传递给我们的插件文件。当我们这样做的时候,通常的WordPress初始化已经发生了(我们在常规post查询之前就中断了)。
add_action( \'init\', \'wpse9870_init_internal\' );
function wpse9870_init_internal()
{
add_rewrite_rule( \'my-api.php$\', \'index.php?wpse9870_api=1\', \'top\' );
}
add_filter( \'query_vars\', \'wpse9870_query_vars\' );
function wpse9870_query_vars( $query_vars )
{
$query_vars[] = \'wpse9870_api\';
return $query_vars;
}
add_action( \'parse_request\', \'wpse9870_parse_request\' );
function wpse9870_parse_request( &$wp )
{
if ( array_key_exists( \'wpse9870_api\', $wp->query_vars ) ) {
include \'my-api.php\';
exit();
}
return;
}