I am trying to add a custom rewrite rule with a single variable to a specific page. The ‘ugly’ version is http://example.com/used-cars/car/?carname=name-of-car
and the ‘pretty’ version I’m going for is http://example.com/used-cars/car/name-of-car
.
http://example.com/used-cars/car/
is a page with a custom template that doesn’t display anything if the carname
variable is not set. This is the code I have so far:
add_filter('query_vars', 'ip_add_rewrite_query_vars');
function ip_add_rewrite_query_vars($query_vars) {
$query_vars[] = 'carname';
return $query_vars;
}
add_action('init', 'ip_add_rewrite_rules');
function ip_add_rewrite_rules() {
add_rewrite_rule(
'used-cars/car/([^/]+)/?$',
'index.php?p=403&carname=$matches[1]',
'top'
);
}
With this, when I go to http://example.com/used-cars/car/name-of-car
it just redirects to http://example.com/used-cars/car
and get_query_var('carname')
returns null
.
I have tried a couple of different variations on ways to do this (like modifying $wp_rewrite
directly, using add_rewrite_tag()
), but I either get the same result or a 404 error. I flush the rewrite rules and my browser’s cache every time I try to test the page again. I installed the rewrite analyzer plugin and my rewrite appears there and looks correct compared to the default ones. As far as I can see from all the examples on the web the code I have should work – it’s pretty much the same example from the codex page – and I have no idea why it doesn’t.
This is a multisite setup (each site on a different subdomain) – I’m not really familiar with multisite but I don’t think there’s anything in that that would affect custom 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:
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: