Regenerate rewrite rules of WordPress permalinks

When installing a theme or plugin, it may be desirable or even necessary for WordPress to regenerate the permalinks. Below are some code examples that do this when activating a plugin or theme.

plugin

Use the following code to recreate the rewrite rules when activating and deactivating a plugin:

register_deactivation_hook( __FILE__, 'sw_flush_rewrites' );
register_activation_hook( __FILE__, 'sw_flush_rewrites' );

function sw_flush_rewrites() {
    // the registration of a CPT needs an additional 'init' hook
    myplugin_custom_post_types_registration();
    flush_rewrite_rules();
}

theme

To recreate the rewrite rules when changing the theme, use the following code:

add_action( 'after_switch_theme', 'flush_rewrite_rules' );