0

I have a standard page setup at http://mysite.com/mypage/

I'd like to setup a rewrite rule in my theme functions that takes any URLs such as:

http://mysite.com/mypage/helloworld/ <-- Currently shows "Not Found"

And translates it into:

http://mysite.com/mypage/?var=helloworld <-- Currently shows the standard page

NOTE ADDED:

"helloworld" is an unknown variable value, so I want ALL "/mypage/" urls to rewrite back, for example: http://mysite.com/mypage/abc/ http://mysite.com/mypage/1231241/ http://mysite.com/mypage/sdfasfdadsf/

Will all rewrite back to http://mysite.com/mypage/?var={path}

2
  • ís this just for /mypage/ or also for another urls? Commented Feb 26, 2013 at 8:58
  • Only for /mypage/
    – David B
    Commented Feb 26, 2013 at 8:58

1 Answer 1

1

As the question was modified, I modify my answer. This task is relatively easy, doable just with a single rewrite rule, which converts everything after /mypage/ string into a variable - I call it var. As this is added to query_vars via hook, is reachable via global $wp_query; echo $wp_query->var;.

add_filter( 'query_vars', 'binda_query_vars' );
function binda_query_vars( $vars ) {
    $vars[] = 'var';
    return $vars;
}

add_action( 'generate_rewrite_rules', 'binda_rewrite_rules' );
function binda_rewrite_rules( $wp_rewrite ) {           
   $mypage_id = 4; //setup your 'mypage' ID
    $wp_rewrite->rules = array(             
        'mypage/(.+?)/?$' => $wp_rewrite->index . '?page_id='.$mypage_id.'&var=' . $wp_rewrite->preg_index( 1 ),        
    ) + $wp_rewrite->rules;
}
6
  • "helloword" is an unknown variable, please see note added to my question.
    – David B
    Commented Feb 26, 2013 at 8:51
  • this completely changes the question Commented Feb 26, 2013 at 8:56
  • see modified answer above Commented Feb 26, 2013 at 9:04
  • Thanks! It's worth noting that i had to remove the leading '/' for it to work: $wp_rewrite->rules = array( 'mypage/(.+?)/?$' => $wp_rewrite->index . '?page_id='.$mypage_id.'&var=' . $wp_rewrite->preg_index( 1 ), ) + $wp_rewrite->rules;
    – David B
    Commented Feb 26, 2013 at 9:13
  • I'm sorry for that little issue. Wouldn't you mind to mark the answer as correct, please? Commented Feb 26, 2013 at 9:18

Your Answer

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

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