Learn how to modify the URL of the taxonomies and categories of a Custom Post Type (CPT) in WordPress using a code snippet.
Now that you know how to create a CPT for Genesis Framework using code, you will discover how to change the URLs of its categories.
In a previous tutorial I showed you how to create a plugin that registers a new Custom Post Type and also add categories (custom taxonomies) to it.
The slug was defined this way for the CPT:
rewrite' => array(
slug' => __('portfolio', 'cg-cpt-portfolio' ),
And so on for the category:
'rewrite' => array(
slug' => __('category-portfolio', 'cg-cpt-portfolio' ),
Therefore, if you had a category called “Web development” in your portfolio, the file page of that category would have the following url:
https://yourwebsite.com/portfolio/category-portfolio/web-development/
Obviously, you can replace “category-portfolio” with the text you want, but…
What if you want your URL to be https://yourwebsite.com/portfolio/web-development/?
In that case, this is what you have to do:
Instructions to customize the URL of a CPT’s categories
To get the URL structure you saw above you need to do 2 things:
1. Modify the functions.php file
Add the following code that manages redirects at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
This code will ensure that the structure of the URL is https://yourwebsite.com/cpt-name/category-name/.
2. Use the same slug for CPT and taxonomy
Finally, make sure that when you register the category you use the same slug as for the CPT.
In the above example this would be:
'rewrite' => array(
slug' => __('portfolio', 'cg-cpt-portfolio' ),
You got it.
If you have more than one CPT you can apply the same logic to display the desired URL structure.
3. Other considerations
To be able to see if the changes have taken effect, be sure to update the permanent links.
You have 2 ways to do this:
- Go to Settings > Permalinks and click “Save changes”.
- If you are using the CPT plugin made by code, you can also disable and re-enable it. This will update the links itself.
Finally, this tutorial is also useful if you are using a plugin from the WordPress repository, as long as you use the same slug to register the CPT and the taxonomy.
If you are not sure, check its code or ask me directly though the contact form (exclusive benefit for subscribers).
Conclusion
Now you know how to modify the URLs of custom categories in your Custom Post Types.
Any questions? If you are a subscriber, let me know in the comments.