Refresh Permalinks Automatically When Post Types Change
Rebuilds the rewrite rules once whenever a post type or taxonomy is added, removed or gets a new slug, so new URLs work without visiting Settings > Permalinks.
Opens WPIDE on
Code
add_action( 'wp_loaded', function () {
$fingerprint = array();
foreach ( get_post_types( array(), 'objects' ) as $type ) {
if ( $type->rewrite ) {
$fingerprint[] = $type->name . ':' . ( $type->rewrite['slug'] ?? '' ) . ':' . (string) $type->has_archive;
}
}
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
if ( $taxonomy->rewrite ) {
$fingerprint[] = $taxonomy->name . ':' . ( $taxonomy->rewrite['slug'] ?? '' );
}
}
sort( $fingerprint );
$hash = md5( implode( '|', $fingerprint ) );
if ( get_option( 'wpide_rewrite_fingerprint' ) !== $hash ) {
flush_rewrite_rules( false );
update_option( 'wpide_rewrite_fingerprint', $hash, true );
}
}, 99 );
Notes
Compares a short fingerprint on each request, which costs almost nothing; the actual rebuild only happens after a change.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.