How to add custom taxonomy in custom post type permalink?
-
I have a custom taxonomy called
campaign
and a custom post type calledasset
. For assets, I want to have the following permalink structure:mysite.com/<campaign_name>/<asset_name>
. I have achieved this by the following code, but now if I go to any normal page with the url structuremysite.com/<pagename>
it gives a 404. And when I comment out the rewrite slug part in the function for registering the custom post type, or add this insteadams/%campaign%
, it works but that’s not the URL structure I want for my custom post type.Code for registering custom taxonomy:
... 'rewrite' => array( 'slug' => '', 'with_front' => true, ), ...
Code for registering custom post type:
... rewrite' => array( 'slug' => '%campaign%', 'with_front' => true, ), ...
Functions for rewrite rules:
function ams_asset_add_rewrite_rules( $rules ) { global $post; if ($post->post_type == 'asset' ) { $new = array(); $new['([^/]+)/(.+)/?$'] = 'index.php?asset=$matches[2]'; $new['(.+)/?$'] = 'index.php?campaign=$matches[1]'; return array_merge( $new, $rules ); } return $rules; } add_filter( 'rewrite_rules_array', 'ams_asset_add_rewrite_rules' ); // Handle the '%campaign%' URL placeholder function ams_asset_filter_post_type_link( $link, $post = 0 ) { if ( $post->post_type == 'asset' ) { $cats = wp_get_object_terms( $post->ID, 'campaign' ); if ( $cats ) { $link = str_replace( '%campaign%', $cats[0]->slug, $link ); } } return $link; } add_filter( 'post_type_link', 'ams_asset_filter_post_type_link', 10, 2 );
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘How to add custom taxonomy in custom post type permalink?’ is closed to new replies.