0

I'm in a bit of a muddle understanding how I can change my $_GET variables into a 'slug'. I already have a setup of a parent-page/child-page using wp_insert_post. BUT! I want to add a variable in-between to create the setup of parent-page/?username=bob/child-page.

I was looking at add_rewrite_rule to change my format from index.php?page_id=PAGE_ID&username=bob to /users/bob/about/.

I've tried this:

public static function add_rewrite(){
    $page=get_page_by_title('users');
    add_rewrite_rule('^users/([a-zA-Z0-9]+)/?','index.php?page_id='.$page->ID.'&username=$matches[1]','top');
}
//quickly to show how called.
add_action('init',array(__CLASS__,'add_rewrite');

This doesn't work but I was hoping to at least achieve users/username/ so that I can figure out how to add my child page later.

Sorry if I'm confusing!!

EDIT!!

I managed to sort out my errors. This is what I've achieved so far:

public static function add_vars($public_query_vars){
    $public_query_vars[]='username';
    return$public_query_vars;
}
public static function addRewriteRule(){
    $page=get_page_by_title('users');
    //add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]','top');
    add_rewrite_rule('^users/([^/]+)/?$','index.php?page_id='.$page->ID.'&username=$matches[1]','top');
}

So now I can access get_query_var('username'); But! I'm still unable to get my child page for the parent page, any ideas? Thanks in advance!

1 Answer 1

0

Found the solution!

I was trying to over complicate things. The best method I've come up with is:

    $users=get_page_by_title('users');
    $about=get_page_by_title('about');
    add_rewrite_rule('^users/([^/]*)$','index.php?page_id='.$users->ID.'&username=$matches[1]','top');
    add_rewrite_rule('^users/([^/]*)/about/?','index.php?page_id='.$about->ID.'&username=$matches[1]','top');

Haven't come up with errors yet, haven't tested yet!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.