6

I see these two methods can be used to create new custom rewrite rule, so under what situation which one is preferred? I suppose they are doing the same thing?

I can either use:

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

or

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

They are totally differents: generate_rewrite_rules is an action hook and add_rewrite_rule is a function. That said, use add_rewrite_rule() if you want to define custom rewrite rules. Use generate_rewrite_rules to perform an action (from codex) "after all rewrite rules have been created".

That doesn't mean that you can not add rewrite rules via generate_rewrite_rules, in fact you can, what it means is that any developer will expect all rewrite rules be set at the moment of generate_rewrite_rules is triggered:

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;
} );

But this will work as expected:

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' );
} );
|improve this answer|||||
  • See my original question for example, they are doing the same. – Yoga Oct 29 '14 at 3:46
  • I've added more explanation. Hope you get the point. – cybmeta Oct 29 '14 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.