Using WP3.1

I Have a custom page with a WP_Query and the query gets dynamic variables from the url. And i want safe variables and clean urls.





I made add_rewrite_rule in to functions.php and it works, but iam not sure it's safe to use this.


  function fcars() {

  add_rewrite_rule('carpage/[/]?([a-zA-Z-]*)[/]?([a-zA-Z-]*)$', 'index.php?pagename=carpage&var1=$matches[1]&var2=$matches[2]');

  add_rewrite_tag('%var1%', '[a-zA-Z]+');
  add_rewrite_tag('%var2%', '[a-zA-Z]+');

add_action('init', 'fcars');

And in Custom template i get the vars

Could someone please help me with this. How can i make this safe to use and is this the right way in WP3.1

What is the right way to make add_rewrite_rule in this case:


(just hyphens and small letters in url) carpage is the static template page.


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()

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.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.