Rewrite rule taxonomy url with different values in one function in WordPress

So I’m a little bit stuck here and honestly don’t know how to proceed, I’m trying to do a rewrite rule to a series of specific urls

I have a movies custom post type and an alphabet taxonomy and the terms A-Z, and I’m trying to make the url from sample.com/alphabet/a to sample.com/movies/a. So I tried this code in functions.php and it works for alphabet A.

Read More
function custom_rewrite_rules() {
    add_rewrite_rule('^movies/a/?', 'index.php?taxonomy=movies_alphabet&term=a', 'top');
}
add_action('init', 'custom_rewrite_rules');

Question: so my question is how to apply it on all alphabet? not just A but also the rest of the alphabets b,c,d,e,f,g,h,j without repeating writing custom_rewrite_rules() function.

Related posts

Leave a Reply

1 comment

  1. You can do that using a subpattern or capturing group like ([a-z]) in your rewrite rule’s regex (i.e. regular expression pattern, which is the 1st parameter for add_rewrite_rule()), and then use $matches[<n>] in your query (the 2nd parameter for add_rewrite_rule()), where <n> is a number (1 or above) and it’s the subpattern’s position number.

    • Why use $matches: Because when matching the current URL against the rewrite rules on your site (i.e. rules which use index.php), WordPress will use preg_match() with the 3rd parameter set to $matches.

    So for example in your case, you can try this which should match movies/amovies/bmovies/c and so on, and that the $matches[1] would be the alphabet after the slash (e.g. c as in movies/c):

    add_rewrite_rule(
        '^movies/([a-z])/?$',
        'index.php?taxonomy=movies_alphabet&term=$matches[1]',
        'top'
    );
    

    Notes:

    • I added $ to the regex, so that it only matches movies/<alphabet> like movies/a and not just anything that starts with that alphabet or path (e.g. movies/aquaman and movies/ant-man).
    • See this for more details on regex meta-characters like that $.
    • You can play with the above regex here( PS: You can learn regex via this site; just check the explanation for the specific regex pattern.. 🙂 )

    Don’t forget to flush the rewrite rules — just visit the Permalink Settings admin page, without having to do anything else.

    Bonus ?

    To support for pagination, e.g. the 2nd page at https://example.com/movies/a/page/2/, you can use the following regex and query:

    Note that we now have 2 capturing groups — ([a-z]) and (\d+) (the page number). $matches[2] is used to get the page number and will be the value of the query var named paged.

    add_rewrite_rule(
        '^movies/([a-z])(?:/page/(\d+)|)/?$',
        'index.php?taxonomy=movies_alphabet&term=$matches[1]&paged=$matches[2]',
        'top'
    );
    

    You can test the regex here, and once again, remember to flush the rewrite rules after making changes to your regex and/or query.