There are 3 parts to making this work.
Register the post type with correct rewrite slug and archive.
We add the %category%
rewrite tag to the slug so we can swap in the selected category. We also specify the archive name explicitly. I’ve omitted the rest of the register_post_type
arguments here, the rest can be as-is in your own example.
'rewrite' => array('slug' => 'posttype1/%category%', 'with_front' => false),
'has_archive' => 'posttype1',
Add a rewrite rule to handle post type / category archive.
add_rewrite_rule(
'posttype1/([^/]+)/?$',
'index.php?post_type=posttype1&category_name=$matches[1]',
'top'
);
This will enable category archive views for your post type. Place both of the above in a function hooked to init
.
Filter post_type_link
to swap in the category name for post permalinks.
function wpd_custom_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) && $post->post_type == 'posttype1' ){
$terms = wp_get_object_terms( $post->ID, 'category' );
if( $terms ){
return str_replace ( '%category%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpd_custom_post_link', 1, 3 );
Repeat the above steps for each post type you want to enable.