I have a wordpress page with Url Slug location. I want to pass a parameter to this page using the format : http://mywpsite.com/location/mylocation

where mylocation will be the parameter passed to zipcode variable. It can be either an integer or string likehttp//mywpsite.com/location/atlanta or http://mywpsite.com/location/345005

I tried using the wordpress rewrite api but it didn't work even after flushing rewrite rules from both code and wp-admin.

Below is the code I tried in my themes function.php:

add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'wp_loaded','my_flush_rules' );

// flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );

//        echo "<pre><code>".  print_r($rules)."</pre></code>";
//        die("SHIVGRE");

    if ( ! isset( $rules['(location)\/([a-zA-Z0-9 ]*)\/?(\d*)?$'] ) ) {
        global $wp_rewrite;

// Adding a new rule
function my_insert_rewrite_rules( $rules )

    $newrules = array();
    $newrules['(location)\/([a-zA-Z0-9 ]*)\/?(\d*)?$'] = 'index.php?pagename=$matches[1]&zipcode=$matches[2]';#&page=$match[3]
    return $newrules + $rules;

// Adding the id var so that WP recognizes it
function my_insert_query_vars( $vars )
    array_push($vars, 'zipcode');
    return $vars;

It didn't work for some reason. Right now my urls work fine with http://mywpsite.com/location?zipcode=atlanta or http://mywpsite.com/location?zipcode=345005

but whenever I try hitting this http://mywpsite.com/location/atlanta then I get redirected to 404 page and my `location' page template is not even called.

It did work with http://mywpsite.com/location/345005 but I receive the zipcode in paged parameter instead.

Any help would be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.