Update: I read that a custom rewrite rule might be overridden and drop any parameter variables, when the custom rewrite rule is used on a child/parent page/post. The post my custom rewrite rule is meant for, is not a child/parent but it is part of a custom post type. Could this be causing similar rewrite issues (dropped parameter variables)?
Update 2 (Problem Solved): As mentioned in the update above, the fact that it concerns a rewrite rule for a custom post type post, was indeed causing the issue. Please see my anwer for the solution.
My question
When using the code below, the actual post rewrite seems to work, as it correctly leads to the post with ID 160
. And it does this even when using a pretty parameter URL. But once the pretty parameter URL is redirected, to the post with ID 160, all parameter values are gone.
How can I get WP to not drop the custom parameter, when using a pretty parameter URL?
So an URL like:
site.com/post/parameter-value/
Should redirect (to the post with ID 160) as follows:
site.com/custom-post-type-slug/post-title-of-160/parameter-value/
(parameter value is not dropped)
The code I'm using
function add_custom_query_vars($vars) {
$vars[] = 'member_view';
return $vars;
}
add_filter('query_vars', 'add_custom_query_vars');
function add_rewrite_rules($rules) {
$newrules = array('page/([^/]+)/?$' => 'index.php?page_id=158&member_view=$matches[1]',
'post/([^/]+)/?$' => 'index.php?p=160&member_view=$matches[1]');
$rules = $newrules + $rules;
return $rules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');
The details
I'm using the code above to rewrite URLs to pretty URLs, ending with pretty custom parameter values. Here's what works and what does not work:
For Pages (this works)
The rewrite rule for pages works. An URL like:
site.com/page/parameter-value/
Redirects (to the page with ID 158) as follows:
site.com/page-title-of-158/parameter-value/
And get_query_var('member_view')
returns parameter-value
.
For Posts (using non-pretty URL) (this works)
For posts the parameters only stick when using "non-pretty" URLs:
site.com/?p=160&member_view=parameter-value
Or:
site.com/custom-post-type-slug/post-title-of-160/?member_view=parameter-value
Both redirect (to the post with ID 160) as follows:
site.com/custom-post-type-slug/post-title-of-160/?member_view=parameter-value
And the member_view
value can be retrieved.
For Posts (using pretty URL) (this does not work)
When using a pretty parameter URL, the custom parameter is dropped after the canonical.php
redirect process is completed. So, an URL that looks like:
site.com/post/parameter-value/
Redirects (to the post with ID 160) as follows:
site.com/custom-post-type-slug/post-title-of-160/
(parameter value is gone)
And both get_query_var('member_view')
and $_GET['member_view']
return nothing.