WordPress Custom URL Rewrites

I do something similar with custom records called shops and their specific ID number.
In my case I want http://example.com/shops/UNIDrecordthatsreallylong

to load with the variable shop_unid being the UNID record.
Here’s my working function:

//Shop page rewrites
function shop_rewrite() {
    add_rewrite_rule('^shops/([^/]*)/?','index.php?pagename=shops&shop_unid=$matches[1]','top');
    add_rewrite_tag('%shop_unid%','([^&]+)');
}
add_action('init', 'shop_rewrite');

Note that I used pagename instead of the post number. You never know if that could change say on a different multisite or if you exported the site to a new server so I always avoid hardcoding to specific post ID’s.

Now on the page or in its own function this should work:

global $wp_query;
$shop_unid = $wp_query->query_vars['shop_unid'];
print_r($shop_unid);

Leave a Comment