Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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' );
}
}
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
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? –  cybnet Sep 2 '13 at 23:39
1  
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 '13 at 0:17
    
Ok, thank you very much. –  cybnet Sep 3 '13 at 1:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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