它们完全不同:generate_rewrite_rules
是一个动作钩和add_rewrite_rule
是一个函数。也就是说,使用add_rewrite_rule()
如果要定义自定义重写规则。使用generate_rewrite_rules
执行操作(来自codex)“在创建所有重写规则之后”。
这并不意味着您不能通过添加重写规则generate_rewrite_rules
, 事实上,您可以,这意味着任何开发人员都希望在generate_rewrite_rules
已触发:
add_action( \'init\', function( ) {
add_rewrite_rule( \'xxx\', \'index.php?xxx\', \'top\' );
} );
add_action( \'generate_rewrite_rules\', function( $wp_rewrite ) {
//All rewrite rules are expected to be set at this moment
if( isset($wp_rewrite->rules[\'yyy\']) ) {
//Ooops. The rewrite rule \'yyy\' is not set
}
} );
//using `generate_rewrite_rules` to add some rewrite rule
add_action( \'generate_rewrite_rules\', function( $wp_rewrite ) {
//All rewrite rules are expected to be set at this moment
$wp_rewrite->rules = array( \'yyy\' => \'index.php?yyy\' ) + $wp_rewrite->rules;
} );
但这将如预期的那样起作用:
add_action( \'init\', function( ) {
add_rewrite_rule( \'xxx\', \'index.php?xxx\', \'top\' );
} );
add_action( \'generate_rewrite_rules\', function( $wp_rewrite ) {
//All rewrite rules are expected to be set at this moment
if( isset($wp_rewrite->rules[\'yyy\']) ) {
//Aha!! Now the rewrite rule \'yyy\' is correctly set
}
} );
add_action( \'init\', function( ) {
add_rewrite_rule( \'yyy\', \'index.php?yyy\', \'top\' );
} );