December 22nd in Wordpress by pbu .

Problem with Custom rewrite rule in WordPress

I was working with rewriting a custom rule for my wordpress plugin and i had a strange problem.

function aff_add_rewrite_rules( $wp_rewrite )
{
  $new_rules = array(
     '^redirect/([0-9]+)/$' => 'index.php?go=$matches[1]'); //question mark ? resolves the problem

  $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

The above rewrite rule

^redirect/([0-9]+)/$’ => ‘index.php?go=$matches[1]

simply refused to work, but it works for

^redirect/(.+)$’ => ‘index.php?go=$matches[1]

(.+) means anything including alphabets and numbers.

I only wanted the rewrite rule to accept numbers, not just anything and after researching a log, i found that the culprit was ? (question mark).

^redirect/?([0-9]+)/?$’ => ‘index.php?go=$matches[1]

and bingo! it worked! I never used the ? sign in htaccess rules and it appears to be wordpress needs it to parse the rewrite rules properly.

You can always refer to the list of wordpress 2.x rewrite rules while writing your custom rule.

Similar Posts:

Share and Enjoy:
  • del.icio.us
  • digg
  • StumbleUpon
  • Technorati
  • DZone
  • Facebook
  • FriendFeed
  • Reddit
  • RSS
  • Twitter

Leave A Comment.