[WordPress] Custom URL using add_rewrite_rule

In the recent project, the clients would like to have pretty URL for good SEO in WordPress. Since the URL structure for WordPress is pretty limited, I have to try rewriting custom URL for client.

After an hour of googling, I finally came up with this working code:

add_action('admin_init', function() {
  $regex = '(condo|townhome|house)/(.+?)';
  $location = 'index.php?prop_type=$matches[1]&area=$matches[2]';
  $priority = 'top';
  add_rewrite_rule( $regex, $location, $priority );
});

Code explanation: Set custom URL as regular expression in $regex. Then write actual query to send to WordPress in $location.

Tips: Online Playground for Regular Expression in PHP: https://www.regex101.com/

From the code above, I can use /condo/silom to find Condominiums in Silom, or /house/siam to find Houses in Siam (I doubt you will ever find one)

Plugins for Rewrite Rule Testing

Playing with rewrite rule is tricky, because you have to flush rewrite rule everytime you changed something. There are 2 plugins I would recommend for testing rewrite rules.

1) Debug Bar & Debug Bar Rewrite Rule

You need this for checking if which rewrite rule matches with the current URL.

Screen Shot 2559-03-08 at 6.02.49 PM

2) Rewrite Rule Testing

This plugin allows you to flush rewrite rules without having to code it in functions.php yourself. This is super convenience.

Screen Shot 2559-03-08 at 6.05.05 PM

If you would like to learn more about rewrite rules and also tutorial on how to add your custom variable (query_var), you can visit this article (It’s 2 years old, but information is still valid): A Mostly complete guide to Rewrite API


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *