Using WordPress ‘generate_rewrite_rules’ PHP action

The generate_rewrite_rules WordPress PHP action fires after the rewrite rules are generated, allowing you to modify the rewrite rules.

Usage

add_action('generate_rewrite_rules', 'your_custom_function');
function your_custom_function($wp_rewrite) {
  // your custom code here
}

Parameters

  • $wp_rewrite (WP_Rewrite): The current WP_Rewrite instance (passed by reference).

More information

See WordPress Developer Resources: generate_rewrite_rules

Examples

Add Custom Rewrite Rule

Add a custom rewrite rule for a custom post type called “product”.

add_action('generate_rewrite_rules', 'add_product_rewrite_rule');
function add_product_rewrite_rule($wp_rewrite) {
  $new_rules = array(
    'product/([^/]+)/?$' => 'index.php?post_type=product&name=$matches[1]'
  );
  $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

Remove a Rewrite Rule

Remove a rewrite rule for the “author” base.

add_action('generate_rewrite_rules', 'remove_author_rewrite_rule');
function remove_author_rewrite_rule($wp_rewrite) {
  unset($wp_rewrite->rules['author/([^/]+)/?$']);
}

Modify Existing Rewrite Rule

Modify the existing rewrite rule for “category”.

add_action('generate_rewrite_rules', 'modify_category_rewrite_rule');
function modify_category_rewrite_rule($wp_rewrite) {
  $wp_rewrite->rules['category/([^/]+)/?$'] = 'index.php?category_name=$matches[1]&custom_var=value';
}

Change Pagination Base

Change the pagination base from “page” to “browse”.

add_action('generate_rewrite_rules', 'change_pagination_base');
function change_pagination_base($wp_rewrite) {
  $wp_rewrite->pagination_base = 'browse';
}

Add Endpoint to Rewrite Rules

Add a custom endpoint called “json” to the rewrite rules.

add_action('generate_rewrite_rules', 'add_json_endpoint');
function add_json_endpoint($wp_rewrite) {
  $wp_rewrite->add_endpoint('json', EP_PERMALINK | EP_PAGES);
}