Using WordPress ‘page_rewrite_rules’ PHP filter

The page_rewrite_rules WordPress PHP filter allows you to modify the rewrite rules used for the “page” post type archives.

Usage

add_filter('page_rewrite_rules', 'your_custom_function');
function your_custom_function($page_rewrite) {
    // your custom code here
    return $page_rewrite;
}

Parameters

  • $page_rewrite (string[]): An array of rewrite rules for the “page” post type, keyed by their regex pattern.

More information

See WordPress Developer Resources: page_rewrite_rules

Examples

Add a custom rewrite rule

Add a custom rewrite rule for page post type archives:

add_filter('page_rewrite_rules', 'add_custom_page_rewrite_rule');
function add_custom_page_rewrite_rule($page_rewrite) {
    $page_rewrite['custom-page/([^/]+)/?$'] = 'index.php?page=$matches[1]';
    return $page_rewrite;
}

Remove a specific rewrite rule

Remove a specific rewrite rule for page post type archives:

add_filter('page_rewrite_rules', 'remove_specific_page_rewrite_rule');
function remove_specific_page_rewrite_rule($page_rewrite) {
    unset($page_rewrite['some-pattern']);
    return $page_rewrite;
}

Clear all rewrite rules

Clear all rewrite rules for page post type archives:

add_filter('page_rewrite_rules', 'clear_all_page_rewrite_rules');
function clear_all_page_rewrite_rules($page_rewrite) {
    return [];
}

Modify an existing rewrite rule

Modify an existing rewrite rule for page post type archives:

add_filter('page_rewrite_rules', 'modify_existing_page_rewrite_rule');
function modify_existing_page_rewrite_rule($page_rewrite) {
    if (isset($page_rewrite['some-pattern'])) {
        $page_rewrite['some-pattern'] = 'index.php?page=$matches[1]&custom_var=1';
    }
    return $page_rewrite;
}

Log rewrite rules

Log the current page post type rewrite rules:

add_filter('page_rewrite_rules', 'log_page_rewrite_rules');
function log_page_rewrite_rules($page_rewrite) {
    error_log(print_r($page_rewrite, true));
    return $page_rewrite;
}