How to include custom taxonomy term slug in the custom post type permalink or url

In this tutorial, we will see how to include the custom taxonomy slug in the post URL of a custom post type. In the example below I have taken post type as ‘products‘ and taxonomy as ‘product_category

Step 1.

In the site-specific plugin add the following code, make sure you change the name of the function, post type and %product_category% to your needs

What we are doing in this code is that we are introducing a variable %product_category% and when this variable is found in the slug of ‘products‘ post_type, we are replacing it with the term of taxonomy ‘product_category‘ attached to that particular post.

Step 2.

Now, go to CPT UI or in whatever way you have registered the custom post type, and change the rewrite rule to include %product_category% in the slug.

Thats it.

Now all your product posts will automatically get the product_category term assigned to the post in the URL.

 

Updated on Apr 11, 2023