Adding Taxonomy Terms to Custom Post Type URLs

Laurel Johnson

Adding taxonomy terms to custom post type URLs takes a bit of extra work but it can be done with the right combination of settings and rewrite rules.

Here’s a common scenario we encounter.  We have a custom post type that’s assigned a custom taxonomy.  On the frontend of our site, we want to display a page with all of the custom posts, archive pages for the taxonomy terms and the posts themselves.  The URL structures we want these posts and pages to follow is this:

www.ourwebsite.com/custom-post-type = The page that displays all of the custom posts

www.ourwebsite.com/custom-post-type/custom-taxonomy-term  = The custom taxonomy archive page

www.ourwebsite.com/custom-post-type/custom-taxonomy-term/custom-post-slug = An individual custom posts

 

To accomplish this, I usually use the plugin Custom Post Types UI and another called Custom Post Type Permalinks.  You can accomplish the same effect without the use of plugins but I like the admin interfaces that these two plugins provide. First, set up the custom post type using the Custom Post Types UI plugin with these settings:

Hierarchical = true

Rewrite = true

 

Then setup a custom taxonomy with these settings:

Hierarchical = true

Rewrite = true

Rewrite hierarchical = true

Custom rewrite slug = slug of your custom post type

Attach to Post Type = your custom post type

 

Now go to Settings > Permalinks and set the permalinks for your custom post type to be /%<the-slug-for-your-custom-taxonomy>%/%postname%/.  This will filter the URLs for your custom post types so that they follow the desired format.

Now add rewrite rules so that your WordPress application knows where to find the custom posts at their new URLs.  You can add rewrite rules with various plugins or just add an action in your functions file.

function my_url_rewrites_init() {
     global $wp;
 
     // add a rewrite rule for each custom taxonomy term
     add_rewrite_rule('<the custom post type slug>/<the taxonomy term slug>/(.+?)(/[0-9]+)?/?$', 'index.php?<the custom post type slug>=$matches[1]&page=$matches[2]', 'top');
 
     // flush the rewrite rules so that the rewrites take effect
     flush_rewrite_rules(); 
}
add_action('init', 'my_url_rewrites_init');

 

 

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *