WordPress: Add Parent Term Slug to Child Term URL

WordPress: add the parent term slug to child term URLs

By default, terms of a custom hierarchical taxonomy do not include the parent slug in their URL. A child term “Lorem” under the parent “Test” gets the URL /topics/lorem/, not /topics/test/lorem/. Adding the parent slug gives cleaner, more descriptive URLs that reflect the hierarchy.

Problem: When you register your own hierarchical taxonomy, child term URLs don’t include the parent term slug. How do you get URLs like …/test/lorem/?

Solution: Add 'hierarchical' => true to the rewrite argument when registering the taxonomy. This is how the built-in categories already work.

Register the taxonomy with hierarchical rewrite

add_action( 'init', 'helloadmin_register_topics' );
function helloadmin_register_topics() {
    register_taxonomy( 'topic', 'post', array(
        'label'        => __( 'Topics', 'textdomain' ),
        'hierarchical' => true,
        'rewrite'      => array(
            'slug'         => 'topics',
            'hierarchical' => true, // include parent slugs in term URLs
            'with_front'   => false,
        ),
    ) );
}

Note that there are two hierarchical arguments. The top-level one makes the taxonomy hierarchical (terms can have parents, like categories). The one inside rewrite is what puts the parent slugs into the URL.

With this setting, a term structure like:

Topics
└── Design
    ├── Typography
    └── Colour Theory

produces URLs like:

/topics/design/
/topics/design/typography/
/topics/design/colour-theory/

Flush the rewrite rules

After changing rewrite arguments, flush the rewrite rules so WordPress rebuilds the URL patterns: go to Settings → Permalinks and click Save Changes, or run:

wp rewrite flush

NOTE: Changing the URL structure on a live site changes the address of every child term page. WordPress doesn’t redirect old term URLs automatically, so update internal links and menus (wp search-replace helps with links stored in content), and add 301 redirects for pages that are already indexed.