How to attach region identifier to a pretty url?

Referencing this question I was able to resolve this issue:

Need help with add_rewrite_rule

To briefly display the changes I made here it goes, in my theme functions.php I added the following action:

add_action('init','custom_rewrite_rule');
function custom_rewrite_rule(){
    add_rewrite_rule('^student/([^/]*)/','index.php?pagename=student&country=$matches[1]','top');
}

This above allows for my urls to be the pretty form of:

  • {{site_url}}/student/ca/
  • {{site_url}}/student/us/

However this form of url is not recognizable until the permalinks are flushed. To do so go to your wp-admin dashboard, select Settings->Permalinks from the right hand menu screen and press the Save button at the bottom of the main screen.

Now the above urls should work.

Next you want to save the additional var in the url for later use. In the above example it is country. This is done using add_filter in functions.php:

add_filter('query_vars','country_selection');
function country_selection($query_vars){
    $query_vars[]='country';
    return $query_vars;
}

Lastly you might want to access this value later in pages (ie: student.php). To do so use the following:

$wp_query->get('country');

You can echo / var_dump the above variable or store it’s result in another variable for later use.

Leave a Comment