# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rewrite-rules, permalinks, custom-post-types
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-auto-flush-rewrite-rules/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Refresh Permalinks Automatically When Post Types Change" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
