Custom URL Parameter Rewrites in WordPress
Recently, I was building a custom search page in WordPress for a gift idea site, where users could select the occasion (Birthday, Christmas …), the recipient (Women, Girl …) and the maximum price of the gift. In addition, I wanted the URL to be nice and SEO friendly, without query parameters.
Now, creating nice URLs within the confines of what WordPress has to offer out of the box is really simple by means of taxonomy and URL rewrites. But implementing a custom URL structure is a bit more daunting, or so it seemed at first. A bit of research and a solution was at hand, and actually quite simple to do URL Parameter Rewrites in WordPress.For this exercise, let’s assume we want to use the following URL:
This entails variables for occasion, recipient and price. The non-frienly equivalent URL would look like this
Adding Rewrite Tags
First we need to declare the rewrite tags we’d like to use, to make WordPress aware of them. But careful, don’t choose tags that are already in use, otherwise they will get overwritten. These are declared using the add_rewrite_tag function and are best placed inside functions.php.
add_rewrite_tag('%occasion%','([^&]+)'); add_rewrite_tag('%recipient%','([^&]+)'); add_rewrite_tag('%price%','([^&]+)');
Behind the scenes, WordPress will use the non-friendly version and therefore we need the proper regex to filter them out, as in the code above.
Adding Rewrite Rules
Now that tags are in place, we need to add the rewrite rule that rewrites the friendly URL to non-friendly, so that WordPress can actually parse it and extract the values. For this we use the add_rewrite_rule function.
In the above case, we use a page called gifts, and pass our values which we then extract using the $matches variable. We also specify to add this rule at the top of the rewrite stack, so it’s handled first before other rewrites. After adding this code to functions.php, you will have to visit the permalink settings page (/wp-admin/options-permalink.php), this will flush the existing rewrite rule cache.
Extract URL Query Values
On the target page (/gifts), we can now extract the URL values like such.
$occasion = isset($wp_query->query_vars['occasion']) ? $wp_query->query_vars['occasion'] : false; $recipient = isset($wp_query->query_vars['recipient']) ? $wp_query->query_vars['recipient'] : false; $price = isset($wp_query->query_vars['price']) ? $wp_query->query_vars['price'] : false;
And that completes the implementation of custom URL parameter in WordPress. Any validation and security additions are ignored for simplicity.