Using WordPress ‘comments_rewrite_rules’ PHP filter

The comments_rewrite_rules WordPress PHP filter allows you to modify the rewrite rules used for comment feed archives.

Usage

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

Parameters

  • $comments_rewrite (string[]): Array of rewrite rules for the site-wide comments feeds, keyed by their regex pattern.

More information

See WordPress Developer Resources: comments_rewrite_rules

Examples

Adding a custom query variable to the comment feed rewrite rules

This example adds a custom query variable my_var to the comment feed rewrite rules.

add_filter('comments_rewrite_rules', 'add_custom_query_var_to_comment_feed_rewrite_rules');
function add_custom_query_var_to_comment_feed_rewrite_rules($comments_rewrite) {
    $new_rules = array();
    foreach ($comments_rewrite as $regex => $query) {
        $new_rules[$regex] = $query . '&my_var=1';
    }
    return $new_rules;
}

Remove the comment feed rewrite rules

This example removes all comment feed rewrite rules.

add_filter('comments_rewrite_rules', 'remove_comment_feed_rewrite_rules');
function remove_comment_feed_rewrite_rules($comments_rewrite) {
    return array();
}

Add a new custom comment feed

This example adds a new custom comment feed with a custom endpoint, /custom-comment-feed/.

add_filter('comments_rewrite_rules', 'add_custom_comment_feed_rewrite_rules');
function add_custom_comment_feed_rewrite_rules($comments_rewrite) {
    $comments_rewrite['custom-comment-feed/?$'] = 'index.php?feed=comments-custom';
    return $comments_rewrite;
}

Change the default comment feed URL

This example changes the default comment feed URL from /comments/feed/ to /new-comments/feed/.

add_filter('comments_rewrite_rules', 'change_default_comment_feed_url');
function change_default_comment_feed_url($comments_rewrite) {
    $new_rules = array();
    foreach ($comments_rewrite as $regex => $query) {
        $new_regex = str_replace('comments/feed', 'new-comments/feed', $regex);
        $new_rules[$new_regex] = $query;
    }
    return $new_rules;
}

Modify comment feed regex pattern

This example modifies the regex pattern for the comment feed rewrite rules.

add_filter('comments_rewrite_rules', 'modify_comment_feed_regex_pattern');
function modify_comment_feed_regex_pattern($comments_rewrite) {
    $new_rules = array();
    foreach ($comments_rewrite as $regex => $query) {
        $new_regex = str_replace('feed', 'rss', $regex);
        $new_rules[$new_regex] = $query;
    }
    return $new_rules;
}