To serve a URL like /plumbing/chicago/ from WordPress, register a rewrite rule that captures the service and city slugs into query vars, register those vars so WordPress keeps them, then swap in a custom template built from your service and city data. The same toolkit also serves /state/city/ location hierarchies, covered below, along with the doorway-page line you must not cross. Here is the whole spine in a must-use plugin:
<?php
/**
* Plugin Name: TE Service Area Pages
* Plugin URI: https://techearl.com/wordpress-service-area-landing-page-urls
* Description: Routes /service/city/ URLs to a custom template built from service and city data.
* Version: 1.0.0
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
* License: GPL-2.0-or-later
* Text Domain: te-service-area
*/
add_action( 'init', 'te_service_area_rewrite' );
function te_service_area_rewrite() {
add_rewrite_rule(
'^([^/]+)/([^/]+)/?$',
'index.php?te_service=$matches[1]&te_city=$matches[2]',
'top'
);
}
add_filter( 'query_vars', 'te_service_area_query_vars' );
function te_service_area_query_vars( $vars ) {
$vars[] = 'te_service';
$vars[] = 'te_city';
return $vars;
}Two custom query vars (te_service, te_city), one rewrite rule that maps two path segments onto them, and query_vars so WordPress does not strip them on the way through WP::parse_request(). The te_ prefix keeps these from colliding with core query vars and with anything a plugin might register.
Route the matched request to a template
A rewrite rule only rewrites the URL into query vars. It does not decide what renders. Two hooks finish the job: a request filter that turns an unknown service or city into a real 404 before any query runs, and template_include, which returns your own template file for the requests that survive:
add_filter( 'request', 'te_service_area_request' );
function te_service_area_request( $vars ) {
if ( empty( $vars['te_service'] ) || empty( $vars['te_city'] ) ) {
return $vars;
}
// Unknown service or city: a real 404, do not invent a page.
if ( ! te_get_service( $vars['te_service'] ) || ! te_get_city( $vars['te_city'] ) ) {
return array( 'error' => '404' );
}
return $vars;
}
add_filter( 'template_include', 'te_service_area_template' );
function te_service_area_template( $template ) {
$service_slug = get_query_var( 'te_service' );
$city_slug = get_query_var( 'te_city' );
if ( '' === $service_slug || '' === $city_slug ) {
return $template;
}
$service = te_get_service( $service_slug );
$city = te_get_city( $city_slug );
// Belt and braces: the request filter has already 404ed unknown slugs.
if ( ! $service || ! $city ) {
return $template;
}
$custom = locate_template( 'service-area.php' );
return $custom ? $custom : $template;
}The guard clauses matter more than they look, and where they sit matters too. Once the rule has matched, the request carries only te_service and te_city, which WordPress treats as a plain home query, so merely handing the original template back from template_include renders your blog index with a 200, not a 404. Returning array( 'error' => '404' ) from request is what makes WP_Query flag a real 404. That single check is the difference between a finite set of pages you control and an infinite URL space where /anything/anywhere/ returns a soft 200. The latter is exactly the pattern crawlers flag as auto-generated.
Your service-area.php template composes the page from the two records:
<?php
get_header();
$service = te_get_service( get_query_var( 'te_service' ) );
$city = te_get_city( get_query_var( 'te_city' ) );
?>
<main class="service-area">
<h1><?php echo esc_html( sprintf(
/* translators: 1: service name, 2: city name */
__( '%1$s in %2$s', 'te-service-area' ),
$service['name'],
$city['name']
) ); ?></h1>
<?php
// Page-specific body. NOT a template with the city name find-replaced in.
echo wp_kses_post( te_render_service_area_body( $service, $city ) );
?>
</main>
<?php
get_footer();The data model
You need two lookups: services and cities. Keep them as real, editable records, not arrays hard-coded in the template, so a human can write genuine copy per page.
A clean shape is a service custom post type for the services (each with its own editable content), and a cities list as either a second CPT or a structured option. Resolve by slug:
function te_get_service( $slug ) {
$query = new WP_Query( array(
'post_type' => 'service',
'name' => sanitize_title( $slug ),
'post_status' => 'publish',
'posts_per_page' => 1,
'no_found_rows' => true,
) );
if ( ! $query->have_posts() ) {
return false;
}
$post = $query->posts[0];
return array(
'id' => $post->ID,
'name' => get_the_title( $post ),
'body' => $post->post_content,
);
}
function te_get_city( $slug ) {
$cities = get_option( 'te_service_area_cities', array() );
$slug = sanitize_title( $slug );
return isset( $cities[ $slug ] ) ? $cities[ $slug ] : false;
}Both functions return false for an unknown slug, which is what the request guard relies on to 404. Storing cities in an option (a keyed array of slug => array( 'name' => ..., 'lat' => ..., ... )) is fine for a fixed service area of a few dozen towns. If editors need to write paragraphs of local copy per city, make cities a CPT too so each gets a real editor.
If you want each combination to behave like a normal post for WP_Query, sitemaps, and SEO plugins instead of a hand-rolled template_include route, use pre_get_posts to point the main query at the right service post and inject the city as context. That same pre_get_posts technique is how you point one WordPress URL at a different page or post without a redirect when the URL and the content underneath it need to diverge. For a small set of static landing pages the template_include approach is simpler; reach for pre_get_posts only when you genuinely need the main query to be the real thing. The state and city hierarchy below is the pre_get_posts version of the same idea.
State and city location URLs
When the service area is organized by geography rather than by service, the URL shapes become /california/ for a state and /california/los-angeles/ for a city. That needs three pieces: a location custom post type, a hierarchical place taxonomy (states as parent terms, cities as children), and two rewrite rules whose captured segments pre_get_posts turns into a normal main query. I keep it in wp-content/mu-plugins/te-location-urls.php:
<?php
/**
* Plugin Name: TE Location URLs
* Plugin URI: https://techearl.com/wordpress-service-area-landing-page-urls
* Description: Serves /state/ and /state/city/ location URLs from the WordPress root.
* Version: 1.0.0
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
* License: GPL-2.0-or-later
* Text Domain: te-location-urls
*/
add_action( 'init', 'te_location_register' );
function te_location_register() {
register_post_type( 'location', array(
'labels' => array( 'name' => __( 'Locations', 'te-location-urls' ) ),
'public' => true,
'has_archive' => false,
'rewrite' => false, // The rewrites are routed by hand.
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'show_in_rest' => true,
) );
register_taxonomy( 'location', 'location', array(
'labels' => array( 'name' => __( 'Places', 'te-location-urls' ) ),
'public' => true,
'hierarchical' => true, // States are parents, cities are children.
'rewrite' => false,
'show_admin_column' => true,
'show_in_rest' => true,
) );
}
// Build the root rules from the real state slugs, so /about/ or /2024/05/ never match them.
add_filter( 'rewrite_rules_array', function ( $rules ) {
$states = get_terms( array(
'taxonomy' => 'location',
'parent' => 0,
'hide_empty' => false,
'fields' => 'slugs',
) );
if ( is_wp_error( $states ) || ! $states ) {
return $rules;
}
$alt = implode( '|', array_map( 'preg_quote', $states ) );
// Specific before general: /california/los-angeles/, then /california/.
return array(
'^(' . $alt . ')/([^/]+)/?$' => 'index.php?te_state=$matches[1]&te_city=$matches[2]',
'^(' . $alt . ')/?$' => 'index.php?te_state=$matches[1]',
) + $rules;
} );
// A new, renamed or deleted state changes the pattern, so rebuild the rules.
foreach ( array( 'created_location', 'edited_location', 'delete_location' ) as $te_hook ) {
add_action( $te_hook, function () {
flush_rewrite_rules( false );
} );
}
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'te_state';
$vars[] = 'te_city';
return $vars;
} );
// Validate the pair before any query runs: a bad state or a city from another state is a real 404.
add_filter( 'request', function ( $vars ) {
if ( empty( $vars['te_state'] ) ) {
return $vars; // Not a location URL.
}
$state = get_term_by( 'slug', sanitize_title( $vars['te_state'] ), 'location' );
if ( ! $state || 0 !== (int) $state->parent ) {
return array( 'error' => '404' );
}
if ( ! empty( $vars['te_city'] ) ) {
$cities = get_terms( array(
'taxonomy' => 'location',
'slug' => sanitize_title( $vars['te_city'] ),
'parent' => $state->term_id, // The city must belong to this state.
'hide_empty' => false,
) );
if ( is_wp_error( $cities ) || ! $cities ) {
return array( 'error' => '404' );
}
}
return $vars;
} );
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
$state = $query->get( 'te_state' );
if ( ! $state ) {
return; // Not a location URL.
}
$city = $query->get( 'te_city' );
$query->set( 'post_type', 'location' );
$query->set( 'location', $city ? $city : $state );
$query->set( 'posts_per_page', 24 );
} );
register_activation_hook( __FILE__, 'te_location_flush_rules' );
function te_location_flush_rules() {
te_location_register();
flush_rewrite_rules();
}Note the activation hook only fires for a regular plugin; dropped into mu-plugins, run wp rewrite flush once after deploying instead (and after adding your first states, since the rules are built from them). Do not run this alongside the root /service/city/ rule from the top of the page unless the service slugs and state slugs can never overlap; prefixing one of them is the safer call.
Why pre_get_posts and the term check matter
The pre_get_posts callback rewrites the main query to pull location posts for the right term. No second WP_Query, no query_posts(), no template hacks, so pagination, is_paged() and the template hierarchy behave normally.
The guard has to sit in the rewrite rule itself, not in the query. WordPress walks the rewrite rules top to bottom and stops at the first one that matches (WP::parse_request() breaks out of the loop), so a catch-all 'top' rule for ^([^/]+)/?$ would capture /about/, and returning early from pre_get_posts does not send WordPress back to try the page rule. The page simply never loads. Building the alternation from the real top-level location terms means /about/, /contact/ and /2024/05/ never match in the first place, and the created_location, edited_location and delete_location hooks rebuild the pattern whenever a state changes.
The request filter then validates the pair before any query runs. The state must be a top-level term, and the city must be a child of that exact state, so /texas/los-angeles/ returns a 404 instead of quietly serving the California city. Returning array( 'error' => '404' ) from request is the clean way to do that, because WP_Query::parse_query() turns that value into a real 404. If you would rather not rebuild rules when states change, prefix them (^locations/([^/]+)/?$) and the whole collision class disappears at the cost of a longer URL; on a marketing site with dozens of top-level pages, that is usually the right call.
Data model details
'rewrite' => falseon both the post type and the taxonomy. Otherwise WordPress adds its own rules (/location/california/,/?location=california) that compete with the root rules. Own the routing or let WordPress own it, not both.- Term slugs are unique within the taxonomy, not within the parent. Two states can each have a Springfield, but WordPress gives the second one a parent-suffixed slug (
springfield-illinois), so that is the URL segment it gets. Edit the slug by hand if you want something else, and remember the city check above matches slug plus parent. - Register specific before general. Rules are evaluated top to bottom and the first match wins, so the two-segment rule goes before the one-segment rule, and keep
$matches[1]and$matches[2]paired with the right query var. - Tighten the capture to
([a-z0-9-]+)if your slugs allow it, so a malformed request fails the rule instead of running a junk query. - Post meta instead of a taxonomy (two query vars and a
meta_query) is simpler for a tiny fixed dataset, but you lose term archives, the admin term UI and term-based caching, so I use the taxonomy for anything that will grow.
The thin-content rules in the doorway section below apply with extra force here: a state page should summarize the state, link to its cities and show real listings; a city page needs the locations plus hours, addresses and a short human description. Let a place with zero listings return a real 404 rather than an empty loop, emit a self-referential canonical on each page, and interlink the hierarchy (state down to cities, city up to state and across to siblings). Hand-routed URLs are not in your SEO plugin's sitemap automatically, so add them yourself.

curl -I https://example.com/california/
curl -I https://example.com/california/los-angeles/
# A non-place single segment must hit the real page, not the location handler.
curl -I https://example.com/about/
wp rewrite list --format=table | grep -E 'te_state|te_city'Seeing both patterns in wp rewrite list confirms they are registered and flushed.
Read this before you generate a single page: doorway pages
This is the part most "programmatic local SEO" tutorials skip, and it is the part that decides whether the technique helps you or sinks the whole site.
Google's spam policies name two things you can trip here. Doorway pages are pages "created to rank for similar search queries" where the differences are cosmetic, funneling users to the same destination. Scaled content abuse is generating many pages "primarily to manipulate search rankings and not help users," which now explicitly covers programmatic generation. A folder of /plumbing/{city}/ pages where every page is the same 300 words with the city name swapped in is the textbook example of both. Google can and does demote or deindex sites for it, and the March 2024 core and spam updates sharpened the scaled-content rule specifically to catch this pattern at scale.
The mechanism above makes it trivial to mint a thousand pages from twelve services and eighty cities. That is precisely why the honest answer to "should I build these?" is usually "only if you can make each one genuinely worth landing on." If you cannot, do not build them. A handful of strong pages beats a thousand thin ones, and the thousand thin ones can drag the strong pages down with them.
What makes a service-area page legitimate
The test is simple: would this page still be useful if you deleted the templated scaffolding and the matched keyword? If the only thing distinguishing /plumbing/chicago/ from /plumbing/denver/ is the two place names, it is a doorway. Make each page carry real, page-specific value:
- Genuine local specifics. The actual neighborhoods or suburbs you cover, local permit or code quirks (Chicago's plumbing code is famously its own thing), response times and travel for that area, real pricing differences. Facts a competitor in the next town cannot copy.
- Distinct copy, written or meaningfully reviewed by a human. Not the same paragraph with a token swapped. The CPT-per-service, option-or-CPT-per-city model exists so a person can actually write this.
- Real proof for that location. Reviews, completed jobs, photos, and case studies from that city, not stock imagery and a generic testimonial slider.
- A real reason the page exists. You actually serve that city. Inventing pages for cities you do not operate in is the clearest doorway signal there is.
- Indexability that matches reality. Only let pages you have filled out get indexed. A barely-started
/service/city/shouldnoindexuntil it has real content, so half-built pages do not bloat the index. Thin pages that do get crawled tend to land under Discovered and Crawled - currently not indexed in Search Console, and that report is the clearest signal that the pages are not pulling their weight yet.
If you have eight services and you genuinely operate in fifteen towns, that is 120 pages, and 120 substantial, locally-specific pages is a perfectly legitimate site. The technique is fine. The abuse is using it to fake coverage and depth you do not have.
When not to do this at all
Skip it outright if any of these are true: you serve one metro and the "cities" are just neighborhoods that would each get a near-identical page; you cannot commit to writing real per-page content; you would be listing cities you do not actually service; or you are tempted because it is fast to generate a lot of URLs. "Fast to generate a lot of URLs" is the warning sign, not the feature. For a single-location business, one strong location page plus a clear service list will out-rank a pile of thin permutations and carries none of the penalty risk.
Slug collisions and flushing rewrite rules
The catch-all rule ^([^/]+)/([^/]+)/?$ is greedy: it matches any two-segment path, so it can swallow URLs that were meant for real pages, categories, or other post types. Two ways to keep it in its lane:
- Make it more specific. If services live under a known prefix, write the rule as
^services/([^/]+)/([^/]+)/?$so only/services/plumbing/chicago/matches and the rest of the site is untouched. - Build the pattern from your real slugs. WordPress stops at the first rule that matches (
WP::parse_request()breaks out of the loop), so validation after the match cannot hand/about/team/back to the page rule: therequestguard turns it into a 404, which is correct for a fake service URL and wrong for a real child page. If the services must live at the root, generate the alternation from the publishedserviceslugs in arewrite_rules_arrayfilter (^(plumbing|roofing)/([^/]+)/?$) and flush when a service is added or renamed, the same way the state and city rules above are built.
Either way, rewrite rules are cached. A new rule does nothing until the rules are flushed. Do not call flush_rewrite_rules() on init: it is expensive and running it on every request is a real performance problem. Flush once on activation:
register_activation_hook( __FILE__, 'te_service_area_activate' );
function te_service_area_activate() {
te_service_area_rewrite(); // register the rule first
flush_rewrite_rules(); // then flush, once
}During development, the no-code equivalent is visiting Settings > Permalinks and clicking Save, which flushes the rules without changing anything. If a brand-new /service/city/ URL 404s right after you add the rule, an unflushed rewrite cache is almost always why. When a flush does not fix it, work through the full checklist for rewrite rules that refuse to fire, which orders the failure modes by how often they actually bite. The flip side, deciding what should render when a path matches nothing, is its own job; I cover it in catching and routing your own 404s in WordPress.
Verify it works
With the plugin active and the rules flushed, test the routing from the command line before you trust the browser:
curl -sI https://example.com/plumbing/chicago/ | head -n 1
# expect: HTTP/2 200 (a service + city you actually have data for)
curl -sI https://example.com/plumbing/atlantis/ | head -n 1
# expect: HTTP/2 404 (unknown city must NOT return 200)The second check is the important one. A real 404 on a slug you have no content for is what proves your guard clauses work and your URL space is finite. If /plumbing/atlantis/ returns 200, your rule is matching everything and you are one crawl away from an index full of empty permutations. Fix the guard or tighten the rule before you let Google anywhere near it.
They become doorway pages when the only thing separating one from the next is the place name. Google's spam policies define doorway pages as pages built to rank for similar queries with no real difference between them, and scaled content abuse as generating pages primarily to manipulate rankings rather than help users. A folder of city pages with one swapped word per page is both.
They are not doorway pages if each one carries genuine, location-specific value: the actual areas you cover, local code or pricing differences, real reviews and jobs from that city, written or reviewed by a human. The technique is neutral; whether the pages are legitimate depends entirely on whether they help someone searching for that service in that place.
Almost always an unflushed rewrite cache. WordPress caches rewrite rules, so a freshly added rule does nothing until you flush. Flush once on plugin activation with flush_rewrite_rules(), or during development just open Settings, then Permalinks, and click Save.
If flushing does not fix it, the other cause is a guard clause rejecting the request: if te_get_service() or te_get_city() returns false for that slug, the request filter returns a 404 on purpose. Confirm the service and city actually exist in your data.
It can. A pattern like ^([^/]+)/([^/]+)/?$ matches any two-segment path, so it can intercept URLs meant for pages, categories, or other post types.
Two defenses: scope the rule to a known prefix such as ^services/([^/]+)/([^/]+)/?$, or build the pattern from your real service slugs so only those paths match. Validating after the match is not enough on its own: WordPress stops at the first matching rule, so a rejected request becomes a 404 rather than falling back to the page it was meant for.
There is no magic number. The limit is how many pages you can fill with real, distinct, locally-specific content. If you genuinely serve fifteen towns with eight services, 120 substantial pages is fine. If you can only write good copy for ten of those combinations, build ten and stop.
The risk is not the count, it is the thinness. Set half-built pages to noindex until they have real content, and never generate a page for a city you do not actually operate in. Pages that exist only to capture a keyword are the ones that get demoted.
For a small, fixed set of landing pages, add_rewrite_rule plus a template_include swap is the simplest path: you fully control the URL pattern and the template, with minimal moving parts.
Reach for pre_get_posts when you need each combination to behave like a first-class query result, so the main query, sitemaps, and SEO plugins all treat it as a real post rather than a hand-routed template. It is more wiring, so only take it on when you actually need the main query to be the real thing.
Short URLs like /california/los-angeles/ read better and tend to do marginally better in search. The cost is that a root-level rule claims every single-segment path, including /about/ and /contact/. Build the rule from the real state slugs so only those paths match (a check in pre_get_posts is too late, because WordPress has already stopped at the first matching rule), or prefix the rules with a static segment. On a site with many top-level pages, the prefix is usually the right call.
A hierarchical taxonomy (states as parents, cities as children) for anything that will grow: you get term archives, the admin term UI, parent and child terms so two states can each have a Springfield (the second gets a parent-suffixed slug such as springfield-illinois), and term-based caching. Two query vars backed by post meta and a meta_query is simpler only for a tiny, fixed dataset.
See also
- How to Add a Custom Rewrite Rule in WordPress: the foundation for everything above, including how
add_rewrite_rule, query vars, and the flush lifecycle fit together - Make / Model / Year URLs in WordPress: the same multi-segment rewrite pattern applied to catalog and directory sites instead of locations
- Clean Up wp_head in WordPress: once your landing pages are routing, trim the default header bloat so each one ships only the markup it needs
Sources
Authoritative references this article was fact-checked against.
- add_rewrite_rule(): WordPress Developer Referencedeveloper.wordpress.org
- pre_get_posts hook: WordPress Developer Referencedeveloper.wordpress.org
- Spam policies for Google web search (doorway pages, scaled content abuse): Google Search Centraldevelopers.google.com
- register_taxonomy(): WordPress Developer Referencedeveloper.wordpress.org
- WP::parse_request(): WordPress Developer Referencedeveloper.wordpress.org
- WP_Query::parse_query(): WordPress Developer Referencedeveloper.wordpress.org
- wp_unique_term_slug(): WordPress Developer Referencedeveloper.wordpress.org





