Can’t add external rewrites

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.

Related posts

Leave a Reply

1 comment

  1. First off, don’t ever do this:

    add_action('init', 'flush_rewrite_rules');
    

    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:

    <?php
    global $wp_query;
    $wp_query->add_rewrite_tag('%gallery%','([^/]+)', 'gallery=');
    $wp_query->add_rewrite_tag('%album%','([^/]+)', 'album=');
    

    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 of add_rewrite_rule which tells WP where to place the rewrite in prominence. You want top to tell WordPress that this rule should come before the built in rules.

    This works:

    <?php
    add_action( 'init', 'wpse41778_add_rewrite' );
    function wpse41778_add_rewrite()
    {
        add_rewrite_tag('%gallery%','([^/]+)');
        add_rewrite_tag('%album%','([^/]+)');
        add_rewrite_rule(
            '^galleries/([^/]+)/?$', 
            'index.php?pagename=galleries&album=1&gallery=$matches[1]',
            'top'
        );
    }
    

    Provided you flush the rewrite rules. If you drop the rules into a plugin you can use register_activation_hook to flush them.

    <?php
    register_activation_hook( __FILE__, 'wpse41778_flush_rewrite' );
    function wpse41778_flush_rewrite()
    {
        wpse41778_add_rewrite();
        flush_rewrite_rules();
    }
    

    To get the value of the gallery or album query variables you can do this:

    $gallery = get_query_var( 'gallery' );
    $album = get_query_var( 'album' );
    

    Based on your rewrite, your usage is probably going to be something like this:

    <?php
    if( get_query_var( 'album' ) )
    {
        $gallery = get_query_var( 'gallery' );
        // do stuff with $gallery
    }
    

    Here is the rewrite part of that as a plugin.