I am trying to create custom rewrite rules in WordPress so that I can pass data to a page based on what is in the query string.
My page works fine:
/retailers-a-z/?merchant=some_merchant
and then also
/retailers-a-z/?merchant=some-merchant&offer=some-offer
I first tried to create a rewrite rule for this in .htaccess but since realised WordPress has it’s own internal redirection database.. so after a lot of research I managed to come up with the following code… However, it is still not working.. Whenever I try to access
/retailers-a-z/some-retailer
or /retailers-a-z/some-retailer/some-offer
it just loads the home page.
functions.php:
function wp_raz_rules()
{
add_rewrite_rule(
'retailers-a-z/([^/]+)/?$',
'index.php?merchant=$matches[1]',
'top'
);
add_rewrite_rule(
'retailers-a-z/([^/]+)/([^/]+)/?$',
'index.php?merchant=$matches[1]&offer=$matches[2]',
'top'
);
add_rewrite_tag('%merchant%', '([^/]+)');
add_rewrite_tag('%offer%', '([^/]+)');
}
add_action('init', 'wp_raz_rules');
function wp_raz_vars($vars)
{
$vars[] = 'merchant';
$vars[] = 'offer';
return $vars;
}
add_filter('query_vars', 'wp_raz_vars');
I then believe I can access them with get_query_var('merchant')
and get_query_var('offer')
instead of $_GET[]
Any ideas? Thanks:)
Managed to fix it by explicitly defining the page name in the query string.
index.php?pagename=retailers-a-z&merchant=$matches[1]&offer=$matches[2]
Not 100% sure if it is the correct way of doing it.