0

I have the following code:

function b09_custom_rewrite_rule() {
    add_rewrite_rule(
      'utils/([^/]+)/?',
      'index.php?utils=$matches[1]',
      'top'
    );
    flush_rewrite_rules();
}
add_action('init', 'b09_custom_rewrite_rule', 10, 0);

function b09_query_vars( $query_vars ) {
    array_push( $query_vars, 'utils' );
    return $query_vars;
}
add_filter( 'query_vars', 'b09_query_vars' );

function b09_template_redirect(){
    global $wp_query;

    $utils_page = get_query_var("utils");

    var_dump( $utils_page );

    if( $utils_page ):
        // custom function
        exit();
    endif;
}
add_filter( 'template_redirect', 'b09_template_redirect' );

Everything works as expected, but as soon as I remove the line flush_rewrite_rules(), WordPress is disabling the rule on the next reload.

Any Ideas?

1
  • I can not reproduce your issue. It is probably that your problem is any other piece of code in your site.
    – cybmeta
    Jan 7, 2015 at 13:50

1 Answer 1

0

Thanks @cybmeta for your hint. I searched my theme and found an other flush_rewrite_rules(true); on the init hook. I removed this and now the rule is being remembered.

Seemingly, calling the function twice is breaking something. Doesn't really make sense to me, but it works now, so whatever :)

4
  • 1
    Having flush_rewrite_rules in init is a bad idea and will probably slow down your site. You only need to call it once, preferably during the activation of a plugin. Jan 8, 2015 at 4:33
  • You are right, but still it should not break the rewrite rules if called twice.
    – rassoh
    Jan 8, 2015 at 10:35
  • But if its in init its called every time you go to tge site Jan 8, 2015 at 13:54
  • Yes, you are right. That's why I removed it all together.
    – rassoh
    Jan 8, 2015 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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