Skip Navigation

[Resolved] Prepend taxonomy for Custom post type

This support ticket is created 3 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 1 reply, has 2 voices.

Last updated by Waqar 3 years, 1 month ago.

Assisted by: Waqar.

Author
Posts
#2203437

I am trying to prepend the taxonomy for my CPT. For example:
website.com/cpt/tag/title

Can you help me with this?

#2204817

Hi,

Thank you for contacting us and I'd be happy to assist.

To add the term slug to the CPT permalink, you can follow these steps:

1. In your CPT settings, add the taxonomy slug in the rewrite rule, in the format "/%{taxonomy-slug}%". For example, if the taxonomy slug is "book-category", the format will be:


/%book-category%

2. Next, you'll need a custom function attached to the filter "post_type_link", so that the %book-category% part from the URL can be replaced with relevant term's slug.
( ref: https://developer.wordpress.org/reference/hooks/post_type_link/ )

For example:


add_filter('post_type_link', 'book_permalink_structure', 10, 4);
function book_permalink_structure($post_link, $post, $leavename, $sample) {
	$taxonomy_slug = 'book-category';
	if (false !== strpos($post_link, '%'.$taxonomy_slug.'%' )) {
		$taxonomy_type_term = get_the_terms($post->ID, $taxonomy_slug);
		if (!empty($taxonomy_type_term))
			$post_link = str_replace('%'.$taxonomy_slug.'%', array_pop($taxonomy_type_term)->
			slug, $post_link);
		else
			$post_link = str_replace('%'.$taxonomy_slug.'%', 'uncategorized', $post_link);
	}
	return $post_link;
}

Note: you'll replace "book-category", with your actual taxonomy's slug.

The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.

I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar