My Plugin
I implemented a small plugin to be able to show events with a specific custom field in a special order. To have some nice permalinks I also used the add_rewrite_rule function to add those rules. Here is the important part of my plugin:
// Add rewrite rule for event archives on activation
function event_archive_activate() {
add_rewrite_rule( '^(januar|februar|maerz|april|mai|juni|juli|august|september|oktober|november|dezember)([0-9]+)', 'index.php?pagename=event_archive&event_month=$matches[1]&event_year=$matches[2]', 'top' );
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'event_archive_activate' );
// Remove rewrite rule for event archives
function event_archive_deactivate() {
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'event_archive_deactivate' );
// Register the custom query var so WP recognizes it
function event_archive_add_query_vars( $vars ) {
$vars[] = 'event_month';
$vars[] = 'event_year';
return $vars;
}
add_filter( 'query_vars', 'event_archive_add_query_vars' );
The problem
So I upload this plugin, actitave it and the rule is successfully written to the options table. Everything is working just fine and all the permalinks shows the correct pages.
But after a while, the rewrite rule disappears from the rewrite rules in the options table. I searched for another call of the flush_rewrite_rules() function my WordPress directory, but only ma plugin and the core files are using it.
I have no idea where and when the rule is deleted from the options table and how to prevent it in the future. My only solution so far is to deactivate the plugin and reactivate it, to have the rules saved to the options table again.
Solution
// Flush added rewrite rules on activation
function event_archive_activate() {
event_archive_set_rewrite_rules();
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'event_archive_activate' );
// Add rewrite rule for event archive on init
function event_archive_set_rewrite_rules() {
add_rewrite_rule( '^(januar|februar|maerz|april|mai|juni|juli|august|september|oktober|november|dezember)([0-9]+)', 'index.php?pagename=event_archive&event_month=$matches[1]&event_year=$matches[2]', 'top' );
}
add_filter( 'init', 'event_archive_set_rewrite_rules' );