URL Rewrite doesn’t work for nested pages

I am using URL rewrite like this page: unexpected problem in url rewrite

It works without any problem, but when I try to use the same rules for nested page, it doesn’t work. Say, I have two pages named page-a and page-b. page-a is parent for page-b. Now I want to catch the passed variable. The URL structure will be:

page-a/page-b/
page-a/page-b/var1/
page-a/page-b/var1/var2/
page-a/page-b/var1/var2/var3/

So, I created three rules. The full code is as follows:

add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
    $query_vars[] = 'var1';
    $query_vars[] = 'var2';
    $query_vars[] = 'var3';
    return $query_vars;
}

function wpse26388_rewrites_init(){
     add_rewrite_rule(
        'page-a/page-b/([0-9]+)/?$',
        'index.php?pagename=page-b&var1=$matches[1]',
        'top' );

    add_rewrite_rule(
        'page-a/page-b/([0-9]+)/([0-9]+)/?$',
        'index.php?pagename=page-b&var1=$matches[1]&var2=$matches[2]',
        'top' );

    add_rewrite_rule(
        'page-a/page-b/([0-9]+)/([0-9]+)/([0-9]+)/?$',
        'index.php?pagename=page-b&var1=$matches[1]&var2=$matches[2]&var3=$matches[3]',
        'top' );
}
add_action( 'init', 'wpse26388_rewrites_init' );

I am using Rewrite analyzer and the variables get the correct regex values. Now when I go to that page with parameter like page-a/page-b/10/20, the parameters are truncated automatically. get_query_var('var1') doesn’t get anything. So, if I pass 1, 2 or 3 parameter it will always redirect to page-a/page-b/.

Can anyone point me what I’m doing wrong?

I know this regex capture numbers. But I need regex so that anything that comes after page-a/page-b/ will be captured by the query variables. I hope someone can help me with this too.

2 Answers
2

I have found my answer while searching. Thanks to this answer of @Milo: https://wordpress.stackexchange.com/a/50775/23214

pagename must include the full parent/child path. So, I had to change index.php?pagename=page-b... to index.php?pagename=page-a/page-b.... Changed it and works ok.

Here is the Full code:

add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
    $query_vars[] = 'var1';
    $query_vars[] = 'var2';
    $query_vars[] = 'var3';
    return $query_vars;
}

function wpse26388_rewrites_init(){
     add_rewrite_rule(
        'page-a/page-b/([0-9]+)/?$',
        'index.php?pagename=page-a/page-b&var1=$matches[1]',
        'top' );

    add_rewrite_rule(
        'page-a/page-b/([0-9]+)/([0-9]+)/?$',
        'index.php?pagename=page-a/page-b&var1=$matches[1]&var2=$matches[2]',
        'top' );

    add_rewrite_rule(
        'page-a/page-b/([0-9]+)/([0-9]+)/([0-9]+)/?$',
        'index.php?pagename=page-a/page-b&var1=$matches[1]&var2=$matches[2]&var3=$matches[3]',
        'top' );
}
add_action( 'init', 'wpse26388_rewrites_init' );

Leave a Comment