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' );
}
}
properties_add_rewrite_rules
should be hooked toinit
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.