1

I have a strange issue. The custom rewrite rules are registered correctly in my plugin activation hook. But, if I go to the permalinks settings page and clic on "Save changes" I lost the rewrite rules registered by my plugin. I have to deactivate and reactivate my plugin to get the custom rewrite rules back again.

Here my activation and deactivation hook

register_activation_hook( __FILE__ , 'properties_plugin_activation' );
function properties_plugin_activation(){
    create_property_post_type();
    create_properties_taxonomies();
    //add custom rewrite rules and custom vars before flush_rewrite_rules()
    properties_add_rewrite_rules();
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__ , 'properties_plugin_deactivation' );
function properties_plugin_deactivation(){
    flush_rewrite_rules();
}

Here my rewrite rules:

// Register a new vars to be used in the rewrite rules
function properties_add_query_vars( $vars) {
  $vars[] = "action"; // name of the var as seen in the URL
  return $vars;
}
add_filter('query_vars', 'properties_add_query_vars');

// Add the new rewrite rules
function properties_add_rewrite_rules() {
    add_rewrite_rule( 'properties/search/?$' , 'index.php?post_type=properties&action=search' , 'top' );
    $config = new PConfig();
    foreach($config->taxonomies as $taxonomy){
        add_rewrite_rule( 'properties/'.$taxonomy["slug"].'/(.+)/?$' , 'index.php?post_type=properties&'.$taxonomy["slug"].'=$matches[1]' , 'top' );
    }
}

1 Answer 1

2

properties_add_rewrite_rules should be hooked to init so it runs on every request.

Rules can be flushed at any time- loading the permalinks settings page calls flush_rewrite_rules, and your rules weren't added on that request, so they disappear.

2
  • That makes sense but I've read in a lot of sites that the add_rewrite_rules should be called only in activation/deactivation hooks because of possible performance issues of running add_rewrite_rules in every page request. What do you think?
    – cybmeta
    Sep 2, 2013 at 23:39
  • 2
    adding them on every request is fine, it's flushing that shouldn't be done on every request- only activation and deactivation. that's the expensive operation.
    – Milo
    Sep 3, 2013 at 0:17

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.