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 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 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 matchesmovies/<alphabet>
likemovies/a
and not just anything that starts with that alphabet or path (e.g.movies/aquaman
andmovies/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.
Happy coding!