Custom page with variables in url. Nice url with add_rewrite_rule

I think the add_rewrite_tag() is not needed, and can be replaced with adding the variables to the public query vars directly:

// Either directly (in your init hook):
$wp->add_query_var( 'var1' );
$wp->add_query_var( 'var2' );

// Or via a filter:
add_filter( 'query_vars', 'wpse12965_query_vars' );
function wpse12965_query_vars( $query_vars )
{
    $query_vars[] = 'var1';
    $query_vars[] = 'var2';
    return $query_vars;
}

Also, you currently allow one or two slashes in front but none at the back. I think you want to move the /? to the end of the regex. The [a-zA-Z-] part for the slug is also sometimes written as [^/] (everything but a slash), but in this case it probably won’t make a difference.

I would write the rewrite rule like this:

add_action( 'init', 'wpse12065_init' );
function wpse12065_init()
{
    add_rewrite_rule(
        'carpage(/([^/]+))?(/([^/]+))?/?',
        'index.php?pagename=carpage&var1=$matches[2]&var2=$matches[4]',
        'top'
    );
}

The (/([^/]+))? makes the whole group optional, so /carpage, /carpage/honda and /carpage/honda/finland should work, with an optional slash at the end. Because we need an extra group for the /, the variables are in the next capture group, so what was $matches[1] becomes $matches[2] and $matches[2] becomes $matches[4].

If you want to debug your rewrite rules I recommend my Rewrite analyzer plugin, it lets you play with the URL and see the resulting query variables.

Leave a Comment