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' );
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0