我发现这是WordPress文档记录最差的功能之一,所以希望这已经步入正轨,或者会被更熟练的WP\\U重写人员纠正。
因此,基本要点是:
在插件激活期间和刷新规则时,确保将自定义规则添加到列表中期间init
, 使用add_rewrite_tag()
对于规则中的任何自定义查询字符串参数。目的地为index.php?this_is_custom=$matches[1]
, 您必须添加this_is_custom
标记
function wpse_39626_init() {
// these must be added during init. if you haven\'t done
// add_rewrite_tag() for all custom query string vars,
// wordpress will ignore them.
add_rewrite_tag( \'%wpse_thing%\', \'(\\w+)\' );
add_rewrite_tag( \'%wpse_name%\', \'(\\w+)\' );
add_rewrite_tag( \'%wpse_index%\', \'(\\w+)\' );
// manually flushing rules so this code is easier to demo.
// under normal circumstances you would use the plugin
// activation hook. this will eventually call wpse_39626_rules().
flush_rewrite_rules();
}
add_action( \'init\', \'wpse_39626_init\' );
// Normally, this would get called during something like
// your plugin\'s activation hook. See register_activation_hook().
function wpse_39626_activate() {
add_rewrite_rule( \'testing/(\\w+)\\[(\\w+)\\]\', \'index.php?wpse_thing=custom&wpse_name=$matches[1]&wpse_index=$matches[2]\', \'top\' );
flush_rewrite_rules();
}
//register_activation_hook( __FILE__, \'wpse_39626_activate\' );
// Hook into rewrite_rules_array, in case rewrite rules
// are flushed after the plugin is activated.
function wpse_39626_rules( $rules ) {
$new_rules = array();
// Matches: testing/outer[inner]
// wpse_name = outer
// wpse_index = inner
$new_rules[\'testing/(\\w+)\\[(\\w+)\\]\'] = \'index.php?wpse_thing=custom&wpse_name=$matches[1]&wpse_index=$matches[2]\';
// prepend and return rules
return $new_rules + $rules;
}
add_action( \'rewrite_rules_array\', \'wpse_39626_rules\' );
// Here\'s some demo code to intercept the page load
// and do custom functionality when our rewrite rule
// matches. (We\'ll just dump the matched values.)
function wpse_39626_posts( $query ) {
if( ! is_main_query( $query ) ) {
return;
}
if( $query->get(\'wpse_thing\') != \'custom\' ) {
return;
}
var_dump( $query->get(\'wpse_name\') );
var_dump( $query->get(\'wpse_index\') );
die;
}
add_action( \'pre_get_posts\', \'wpse_39626_posts\' );
您的示例对代码有一点了解,尤其是在您试图匹配的URL中(所有这些参数对应的是什么?),所以我的回答有点笼统。