Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 68 ยท Custom Post Types, Taxonomies and Fields

Permalinks and Rewrite Rules

Understand WordPress permalinks and rewrite rules: structure tags, add_rewrite_rule, add_rewrite_tag, query vars, endpoints, template_redirect and when to flush.

A visitor types /books/2024/ or /blog/my-first-post/, but WordPress stores posts in a database and finds them by ID or slug. Something has to translate the pretty path into a query. That something is the rewrite system: a list of regular expressions, each paired with a query string. WordPress tests the requested path against the list from top to bottom, and the first match wins. Its query string becomes the variables for the main query (see how WordPress handles a request).

This lesson explains permalink structures, the rules WordPress generates, how to add your own with add_rewrite_rule() and add_rewrite_tag(), how query variables carry the result into your code, endpoints, and the most common beginner error: flushing the rules at the wrong time.

The real rewrite system runs only inside WordPress, so real code is read-only here. The runnable examples are plain-PHP stand-ins that apply regular expressions the same way and show the ordering behavior. They are simplified models, not core code.

Settings, Permalinks in the admin lets you choose how post URLs look. Behind each choice is a structure made from tags:

Structure Example URL
Plain /?p=123
Day and name /2025/03/14/sample-post/
Month and name /2025/03/sample-post/
Numeric /archives/123
Post name /sample-post/
Custom any mix of tags such as /%category%/%postname%/

The common tags are %year%, %monthnum%, %day%, %postname%, %post_id%, %category% and %author%. For SEO and readability, most sites choose Post name. Tags like %category% make a URL change whenever a post moves to another category, which breaks links, so they are best avoided.

Pretty permalinks need the web server to send unknown paths to index.php. On Apache that is the .htaccess file WordPress writes; on nginx it is a try_files $uri $uri/ /index.php?$args; line in the server config.

When you save a structure, WordPress compiles it, together with the rules for pages, categories, feeds, search, authors, dates and every registered post type and taxonomy, into one ordered array. That array is stored in the rewrite_rules option in wp_options (see the Options API). Reading it is cheap; rebuilding it is expensive, and that is why flushing matters.

flowchart TD
    A["Request: /books/year/2024/"] --> B["Web server: not a real file,<br/>send to index.php"]
    B --> C["WP::parse_request()"]
    C --> D["Walk rewrite_rules top to bottom"]
    D --> E{"Regex matches path?"}
    E -- "no" --> D
    E -- "yes" --> F["Build query string,<br/>fill in $matches[1]"]
    F --> G["Query vars: post_type=book, book_year=2024"]
    G --> H["Main query, then template"]

The first rule whose regular expression matches decides the query variables; later rules are never tried.

Adding your own rule

add_rewrite_rule() takes a regular expression for the path, a query string, and a position:

PHP
<?php
function acme_add_book_year_rule(): void {
    add_rewrite_rule(
        '^books/year/([0-9]{4})/?$',
        'index.php?post_type=book&book_year=$matches[1]',
        'top'
    );
}
add_action( 'init', 'acme_add_book_year_rule' );

Points to notice:

  • The regex has no leading slash and no domain. It is matched against the path relative to the site root, with the trailing slash optional.
  • Use single quotes so PHP does not try to expand $matches. The query string uses $matches[1], $matches[2] and so on for captured groups.
  • The query string starts with index.php? and uses query variable names.
  • The third argument is 'top' or 'bottom' (the default). Core's page rule is a broad catch-all that matches almost any path. A rule added at the bottom comes after it and is never reached, so specific custom rules usually need 'top'.

Because the rules are cached, the code above does nothing until the rules are rebuilt.

Query variables and add_rewrite_tag()

WordPress only keeps query variables it knows about; unknown names from a URL are dropped for safety. Use add_rewrite_tag() to register a new variable and the regex that fits it, which also adds it to the public query vars:

PHP
<?php
add_action( 'init', function (): void {
    add_rewrite_tag( '%book_year%', '([0-9]{4})' );
    add_rewrite_rule(
        '^books/year/([0-9]{4})/?$',
        'index.php?post_type=book&book_year=$matches[1]',
        'top'
    );
} );

If you only need a variable and no tag, add it with the query_vars filter:

PHP
<?php
add_filter( 'query_vars', function ( array $vars ): array {
    $vars[] = 'book_year';
    return $vars;
} );

Read it in a template or hook with get_query_var( 'book_year' ). To act on it you have two good choices: alter the main query in pre_get_posts (best when the page should list posts), or use template_redirect to handle the request yourself.

PHP
<?php
add_action( 'pre_get_posts', function ( WP_Query $query ): void {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    $year = (int) get_query_var( 'book_year' );
    if ( $year > 0 ) {
        $query->set( 'date_query', [ [ 'year' => $year ] ] );
    }
} );

template_redirect fires after the query has run and before a template loads, so it suits custom responses such as a file download or a redirect:

PHP
<?php
add_action( 'template_redirect', function (): void {
    if ( get_query_var( 'book_export' ) === 'csv' ) {
        header( 'Content-Type: text/csv; charset=utf-8' );
        echo "title,year\n";
        exit;
    }
} );

Rules in action: a matcher you can run

This stand-in applies rules the way WordPress does: first match wins, $matches[N] is filled in, and only known query variables survive. It includes simplified versions of two core rules so you can see why 'top' matters.

PHP A rewrite rule matcher that produces query vars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first run shows the trap: the broad page rule matches books/year/2024 as a page called books/year on page 2024, so the custom rule at the bottom is never reached. Putting it on top fixes that. The last run shows the second trap: the rule matched and set post_type, but book_year was dropped because nobody registered it as a query variable.

A structure with tags is translated into a regular expression by replacing each tag with its pattern. This second stand-in builds the regex and query string for a structure and also generates a URL for a post, which is what get_permalink() does in reverse.

PHP From a permalink structure to a regex and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You can see why %postname% alone is such a loose pattern: ([^/]+) matches nearly any single segment. Core therefore keeps its rules in a careful order, and WordPress checks afterwards whether a matched page or post really exists before it shows a 404.

Endpoints

An endpoint adds a suffix to existing URLs, such as /my-post/print/ or /my-post/amp/. Register it with add_rewrite_endpoint() and a mask that says which URLs get it:

PHP
<?php
add_action( 'init', function (): void {
    add_rewrite_endpoint( 'print', EP_PERMALINK );
} );

add_action( 'template_redirect', function (): void {
    // The query var exists but is an empty string on /my-post/print/.
    if ( false !== get_query_var( 'print', false ) && is_singular() ) {
        include get_theme_file_path( 'print-view.php' );
        exit;
    }
} );

The gotcha is in the comment: on /my-post/print/ the print variable is an empty string, which is falsy. Compare with false using !== and a default, as shown, rather than testing truthiness. Other masks include EP_PAGES, EP_ROOT and EP_ALL.

Flush rarely

Rules are rebuilt by flush_rewrite_rules(). That call regenerates the whole array and writes it to the database, so it is slow and must not run on every request. The rules are correct when:

  • the code that registers post types, taxonomies, tags and rules has run, and
  • the stored rewrite_rules option was generated after that code existed.

So flush once, at the moment the registrations change:

PHP
<?php
register_activation_hook( __FILE__, function (): void {
    acme_register_book_post_type();   // register first
    acme_add_book_year_rule();
    flush_rewrite_rules();            // then flush, once
} );

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );

Registering first matters because the flush only knows about what is registered right now. Running it from init slows every page load and, on busy sites, can cause database contention. While developing you can simply visit Settings, Permalinks and press Save, or run wp rewrite flush (see WP-CLI). Activation and uninstall covers the hooks.

Common mistakes

  • Calling flush_rewrite_rules() on init. It rebuilds all rules on every request.
  • Adding a specific rule at the bottom. A catch-all page rule gets there first.
  • Forgetting the query variable. The rule matches, but the variable is dropped.
  • Using double quotes. PHP replaces $matches before WordPress sees it.
  • Leading slash in the regex. The path has none, so nothing matches.
  • Testing endpoint variables for truthiness. An empty string means "present".
  • A 404 on a new post type. Flush once, or save the Permalinks screen.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which rule does WordPress use when several regular expressions match the requested path?

    WordPress walks the rewrite rules from top to bottom and stops at the first match, so order decides the result.
  2. 2. Why does add_rewrite_rule() often need the third argument 'top'?

    Rules added at the bottom come after core's catch-all page rule, so a specific custom path never reaches them.
  3. 3. When should you call flush_rewrite_rules() in a plugin?

    Flushing rebuilds and saves every rule, which is expensive. Do it once when the registrations change.
  4. 4. A custom rule matches the URL but get_query_var( 'book_year' ) is empty. What is the likely cause?

    WordPress drops query variables it does not know. Register the variable so it survives parsing.
  5. 5. Why must you write the query string of add_rewrite_rule() in single quotes?

    In double quotes PHP treats $matches as a variable. In single quotes the text stays literal so WordPress can fill in the captured groups.

Summary

  • Rewrite rules are an ordered list of regex and query string pairs stored in the rewrite_rules option; the first match wins.
  • Permalink structures are built from tags like %year% and %postname%; post name is the usual choice.
  • add_rewrite_rule() adds a rule, add_rewrite_tag() or the query_vars filter registers its variable, and get_query_var() reads it.
  • Use 'top' for specific rules so core's catch-alls do not swallow them.
  • Handle requests in pre_get_posts to change the main query, or in template_redirect to take over the response.
  • Endpoints add suffixes to existing URLs; an empty value still means the endpoint is present.
  • Flush rules only on activation and deactivation, after registering everything.
  • The runnable code is a stand-in that models matching and ordering.

Next: Shortcodes