1

I'm building a site where every state and city in the US has a landing page. I have a database of every city, state, and zip code, set up as a custom post type in WP. Here's what I've done successfully to create a landing page for every state:

function em_rewrite_rules($rules) {
    $newrules = array();
    $newrules['state/(.*)/?'] = 'index.php?state=$matches[1]';
    return $newrules + $rules;
}
add_filter('rewrite_rules_array','em_rewrite_rules');

function em_query_vars($vars) {
    array_push($vars, 'state');
    return $vars;
}
add_filter('query_vars','em_query_vars');

function em_templates($template) {

    global $wp_query;
    if (isset($wp_query->query_vars['state'])) {
        return dirname(__FILE__) . '/single-state.php';
    }

    return $template;
}

add_filter('template_include', 'em_templates', 1, 1);

This is working great. Every page is dynamically generated based on the content in single-state.php.

Now I need to support cities, in the format:

http://example.com/state/new-york/albany/

I've found so many examples of different ways to create rewrite rules, but all of them follow a different format than what I already have. It took me many hours to get the working example above. Can someone propose a way I could achieve the URL format above and load a custom template when a city is specified?

2

Wasn't as hard as I thought. Here's the working example, in case anyone finds it helpful:

function em_query_vars($vars) {
    array_push($vars, 'state');
    array_push($vars, 'city');
    return $vars;
}

add_filter('query_vars','em_query_vars');

function em_rewrite() {

    add_rewrite_rule( '^state/([^/]*)/([^/]*)/?', 'index.php?state=$matches[1]&city=$matches[2]', 'top' );
    add_rewrite_rule( '^state/([^/]*)/?', 'index.php?state=$matches[1]', 'top' );
    add_rewrite_tag('%state%','([^&]+)');
    add_rewrite_tag('%city%','([^&]+)');

}

add_action('init', 'em_rewrite');

function em_templates($template) {

    global $wp_query;
    if (isset($wp_query->query_vars['state']) && isset($wp_query->query_vars['city'])) {
        return dirname(__FILE__) . '/single-city.php';
    } elseif (isset($wp_query->query_vars['state'])) {
        return dirname(__FILE__) . '/single-state.php';
    }

    return $template;
}

add_filter('template_include', 'em_templates', 1, 1);

Your Answer

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

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