I’ve got the following code in my functions.php
function add_custom_rewrite_rules(){
add_rewrite_tag('%gallery%','([^/]+)', 'gallery=');
add_rewrite_tag('%album%','([^/]+)', 'album=');
add_rewrite_rule('galleries/(.+)/?$' , 'index.php?pagename=galleries&album=1&gallery=$matches[1]');
}
add_action('init', 'flush_rewrite_rules');
add_action('init', 'add_custom_rewrite_rules');
But the rewrite rule is not getting added, and it doesn’t show up in my list of rewrites in the admin.
First off, don’t ever do this:
Every time WordPress loads, you are going to flush the rewrite rules. You only need to do this once to make sure your rewrite shows up.
Second,
add_rewrite_tag
only takes two arguments, the tag and the regex. If you want to specify a query variable directly, you’ll need to do something like this:In your case, it doesn’t really matter: you’re using the same query variable as the tag.
Finally, there were some errors in your regex. You need to start with a carrot, and I wouldn’t use
(.*)
for second part. You also need to specify the third argument ofadd_rewrite_rule
which tells WP where to place the rewrite in prominence. You wanttop
to tell WordPress that this rule should come before the built in rules.This works:
Provided you flush the rewrite rules. If you drop the rules into a plugin you can use
register_activation_hook
to flush them.To get the value of the
gallery
oralbum
query variables you can do this:Based on your rewrite, your usage is probably going to be something like this:
Here is the rewrite part of that as a plugin.