For one of my CPT, when default permalink looks like
example.com/CPT_slug/%postname%
instead I would like a permalink like this :
example.com/%custom_taxonomy_term%/CPT_slug/%postname%
With regular categories and posts, it's easy to do, I just have to use %category%/%postname% for permalinks.
But I can't for the life of me achieve it for CPT and custom taxonomies. What am I doing wrong ?
My CPT slug is "activity", with posts like : "Food tour", "Dinner cruise", ... My Custom Taxonomy slug is "agence", with terms like "New York", "Miami", ...
So I'd like my URLs to be like
- https://www.example.com/new-york/activity/food-tour
- https://www.example.com/new-york/activity/dinner-cruise
- https://www.example.com/miami/activity/food-tour (different post from the first)
(where, ideally, in case of "same slug" situations, disambiguation would be dealt with)
I've tried this approach :
"rewrite" => array( "slug" => "%agence%/activity", "with_front" => false ),
in register_post_type
and
function add_agence_prefix_in_activity_url( $post_link, $id = 0 ) {
$post = get_post( $id );
if ( is_object( $post ) && get_post_type($post) == 'activity' )
{
$terms = wp_get_object_terms( $post->ID, 'agence' );
if ( $terms ) {
return str_replace( '%agence%', $terms[0]->slug, $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'add_agence_prefix_in_activity_url', 1, 3 );
It works : it lets me display my "activity" post content.
But I get 404 errors when trying to display posts & pages with their usual /%postname% permalinks; and I don't know what to do to fix this.
So instead I tried using the plugin "Custom Post Type Permalinks" :
it almost works : pages & posts are not broken anymore, and it gives me URLs like
https://www.example.com/activity/**new-york**/food-tour
... whereas I would like
https://www.example.com/**new-york**/activity/food-tour
So i'm almost there, but not quite. How should I proceed ? Is what I am trying to do even possible ?