How to view and modify WordPress rewrite rules

If you encounter a sudden unexpected delay in page load which was previously working fine, a good place to check is the rewrite rules.

In my case, it seems there was some issue in the currently generated rules which was causing this delay.

A simple visit to Settings->Permalink automatically flushed and regenerated all the rewrite rules and it resolved the issue for me. The page is again loading as fast as it did earlier.

However, if you want to check the current rewrite rules, there is a simple code to check that.

Add the below code to your plugin or theme.

// Filter to display rewrite rules on permalink settings page when debugging 
add_filter( 'rewrite_rules_array', 'show_all_the_rewrite_rules' );
function show_all_the_rewrite_rules( $rules ) {
    echo nl2br( var_export( $rules, true ) );
    die;
}

Now this hook is only called on Permalink Settings page. So, visit that page and you will be able to see all the current rewrite rules of your website.

You can also remove rules if they are not required, based on regex as shown in the following code.

// Filter hook to remove unwanted rewrite rules, will only run when **setting->permalink** page is opened
function remove_rewrite_rules( $rules ) {
    foreach ( $rules as $rule => $rewrite ) {
        if ( preg_match( '/(feed|rss|atom|embed|attachment|trackback|year|date|search/)/', $rule ) ) {
            unset( $rules[$rule] );
        }
    }

    return $rules;
}

You can define any pattern in the preg_match function to remove the unwanted rewrite rules.

Hope this helps.

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *