Question

I'm trying to get a subpage from a normal WordPress page with add_rewrite_rule

The page is located at http://example.com/mypage

The subfolder is something like http://example.com/mypage/sub1 but can sub2, sub3or sub4 (name is known)

The page name mypage (slug) is not known but the page id

Currently I'm stuck with this: (simplified)

add_action ( 'init', 'my_init' );
add_action ( 'query_vars', 'my_query_vars' );

function my_init(){
    add_rewrite_rule( '([^/]+)/(sub1|sub2|sub3|sub4)/?', 'index.php?my_page=$matches[2]', 'top');
}
function my_query_vars($vars) {
    $vars[] = "my_page";
    return $vars;
}

if I goto http://example.com/mypage I'm on that page (obviously) but going to mypage/sub1end up on the homepage

Was it helpful?

Solution

The answer is pretty simple. This is the modified my_init function:

function my_init(){
    add_rewrite_rule( '([^/]+)/(sub1|sub2|sub3|sub4)/?', 'index.php?pagename=$matches[1]&my_page=$matches[2]', 'top');
}

please note the pagename variable which holds the name (slug) of the current page

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top