GENERATE_REWRITE_RULES(操作)与ADD_REWRITE_RULE(函数):哪一个是首选的?

时间:2014-10-28 作者:Yoga

我看到这两种方法可以用来创建新的自定义重写规则,那么在什么情况下首选哪种方法呢?我想他们也在做同样的事情?

我可以使用:

add_action( \'generate_rewrite_rules\', function( $wp_rewrite ) {
    $wp_rewrite->rules = array( \'xxx\' => \'index.php?xxx\' ) + $wp_rewrite->rules;
} );

add_rewrite_rule( \'xxx\', \'index.php?xxx\', \'top\' );

1 个回复
SO网友:cybmeta

它们完全不同: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\' );
} );

结束

相关推荐