Why does rewrite rule work for page not for custom post type post?

Well, I found the solution. It seems that, when applying a rewrite rule on a custom post type post, one needs to tell WP the custom post type’s name within the rewrite rule itself.

Here’s the code that does NOT work (redirects and drops parameter variables instead of rewrite):

function add_rewrite_rules($rules) {
    $newrules = array('cpt-slug/([^/]+)/([^/]+)/?$' => 'index.php?p=$matches[1]&member_view=$matches[2]');
    $rules = $newrules + $rules;
    return $rules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

Here’s the code that DOES work (rewrites and keeps parameter variables):

function add_rewrite_rules($rules) {
    $newrules = array('cpt-slug/([^/]+)/([^/]+)/?$' => 'index.php?p=$matches[1]&post_type=cpt_name&member_view=$matches[2]');
    $rules = $newrules + $rules;
    return $rules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

The rewrite worked once &post_type=cpt_name was added to its rule. I’m amazed that this isn’t/wasn’t explicitly pointed out in any of the rewrite rules-related info I found and read (and I searched for 2 days) 🙂

An URL that looks as follows:

site.com/cpt-slug/INSERT-ID-OF-CPT-POST/INSERT-PARAMETER-VARIABLE/

Will now rewrite properly and the parameter variables will not be dropped. The parameter variable can now be retrieved using get_query_var('member_view').

Leave a Comment