I have a page created (page ID 235
) with a page template that will need to be passed a variable. I would like to pass this variable through the URL. My first attempt was to pass this with a GET variable, and that worked just fine.
URL: http://example.com/sok/events/?kategori=variablehere
Now, I thought I’d spice this up a bit and prettify it. This is what I am aiming to achieve:
URL: http://example.com/sok/events/variablehere
The code I have been using in my attempt looks like the following:
function setup_filter_rewrites() { add_rewrite_tag('%kategori%','([^&]+)'); add_rewrite_rule('^sok/events/([^/]*)/?', 'index.php?p=235&kategori=$matches[1]', 'top'); } add_action( 'init', 'setup_filter_rewrites' );
Now, when accessing the URL above, I am redirected to http://example.com/sok/events/
– i.e. the URL but without the query variable. Obviously, as you may guess, the query variable is not accessible inside the page.
I heard of the redirect_canonical
function potentially causing problems with rewrite rules, so I disabled it. After having done so, accessing the above URL instead yields a 404.php request.
As you can see, I’ve really tried to cut back on the code to make it as simple as possible as well as using the correct API functions. I have checked the rule with A tool to analyze rewrite rules? and it reports the variable as being public and accessible. I tried cutting the page down to a simple echo $wp_query->query_vars['kategori']
but that did not output anything nor did it prevent the redirection.
I suspect the redirection is the problem here – if I could stop it, I’m confident I’d be able to grab the query variable.
This problem is similar to URL Rewrite + Page + Custom Post Type = Unusual Redirect and Querystring parameter getting lost in rewrite rule insofar that it is also a redirection error. However, in my case, I am not dealing with custom post types of any kind.
I think you just have to add
kategori
to the array of query vars:EDIT- after much iteration we’ve arrived at a solution. the original code seemed to be working, but only with specific permalink settings, as I was mistakenly routing to a post instead of a page. rather than
p=
, it should bepagename=
, with both the parent and child page in the path: