generate_rewrite_rules (action) vs add_rewrite_rule (function): which one is preferred?

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

Leave a Comment