WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 11 down vote accepted

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.

share|improve this answer
Thank you. This helpped me a lot – ide79 Mar 25 '11 at 9:11
Many thanks sir! – Alexandre Bourlier Jun 11 '14 at 18:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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