My Plugin
我实现了一个小插件,能够以特殊顺序显示具有特定自定义字段的事件。为了获得一些好的永久链接,我还使用了add\\u rewrite\\u rule函数来添加这些规则。以下是我的插件的重要部分:
// 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
所以我上传了这个插件,激活它,规则成功写入选项表。一切正常,所有的永久链接都显示了正确的页面。
但一段时间后,重写规则从选项表中的重写规则中消失。我搜索了flush\\u rewrite\\u rules()函数my WordPress directory的另一个调用,但只有ma插件和核心文件在使用它。
我不知道该规则在何时何地从选项表中删除,也不知道将来如何防止。到目前为止,我唯一的解决方案是停用插件并重新激活它,将规则再次保存到选项表中。
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\' );