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.
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.
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 foradd_rewrite_rule()
), and then use$matches[<n>]
in your query (the 2nd parameter foradd_rewrite_rule()
), where<n>
is a number (1
or above) and it’s the subpattern’s position number.$matches
: Because when matching the current URL against the rewrite rules on your site (i.e. rules which useindex.php
), WordPress will usepreg_match()
with the 3rd parameter set to$matches
.So for example in your case, you can try this which should match
movies/a
,movies/b
,movies/c
and so on, and that the$matches[1]
would be the alphabet after the slash (e.g.c
as inmovies/c
):Notes:
$
to the regex, so that it only matchesmovies/<alphabet>
likemovies/a
and not just anything that starts with that alphabet or path (e.g.movies/aquaman
andmovies/ant-man
).$
.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 namedpaged
.You can test the regex here, and once again, remember to flush the rewrite rules after making changes to your regex and/or query.