Custom Permalink Structure for Taxonomies Added to Custom Post Types

This tutorial provides the PHP code you can use if you want to create your own custom permalink structure for custom taxonomy types you add to your custom post types.

You can go from this:

http://example.com/golf-course/british-open-golf-championship/

to this

http://example.com/golf-course/scotland/st-andrews/british-open-golf-championship/

The code in this post creates a custom post type named Golf Courses which includes 2 taxonomy types named Country and Region as seen in the following screen shot:

custom-permalink-structure

The permalink structure in this example will be:

your domain / custom post type / taxonomy / taxonomy / post name

The code adds the ability to create custom taxonomies like country and region. You can add unlimited taxonomies for each custom post type. You can also display any number of taxonomies in your permalink structure.

Basically, the code enables you to add 1 or more taxonomy types to your permalink structure for custom post types.

Here’s the code you simply paste at the end of your child themes functions file:

Make sure you re-save your Permalinks after adding the following code.

Issues

The above solution will return a 404 error on your CPT archive page. The reason for this is because we used tags to rewrite the slug in the register_post_type function, as follows:

'slug' => 'golf-course/%country-type%/%region-type%',

If you remove the tags for each taxonomy, your CPT archive will work however you will lose the custom permalink structure.

To fix this, you can:

  1. Create a custom loop and rebuild the CPT archive fairly easily
  2. Use another method which doesn’t re-write the CPT slug

Alternative Method for Using post_type_link Filter

The following method enables you to add a default slug for each taxonomy if none assigned :

The above alternative only relates to the use of the filter and not the entire solution.

Related Tutorials

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.