以下是我一直在使用的技巧:
使用数组存储重写,对数组进行哈希运算,将哈希数组存储为选项,检查存储的选项是否与当前重写哈希匹配;如果不是,请更新“重写”代码段(这是一个起点,而不是成品):
add_action( \'init\', \'wpse_393260_rewrites\' );
function wpse_393260_rewrites() {
// Array of rewrites.
$my_rewrites = array(
\'foo/([a-z0-9-]+)[/]?$\' => \'index.php?foo=$matches[1]\',
\'bar/([a-z0-9-]+)[/]?$\' => \'index.php?bar=$matches[1]\',
// etc.
);
// Implements the rewrite rules.
foreach ( $my_rewrites as $regex => $query ) {
add_rewrite_rule( $regex, $query, \'top\' );
}
// Hashes the $my_rewrites array.
$hashed_rewrites = md5( serialize( $my_rewrites ) );
// Gets the currently-active rewrites from the option.
$my_current_rewrites = get_option( \'my_rewrites_option\' );
// If anything\'s changed, flush the rewrites and update the option.
if ( $my_current_rewrites !== $hashed_rewrites ) {
flush_rewrite_rules();
update_option( \'my_rewrites_option\', $hashed_rewrites );
}
}