Here’s the method I use to get what you’re trying to achieve.
First, register your location taxonomy:
register_taxonomy(
'location',
array( 'business' ),
array(
'rewrite' => array( 'slug' => 'business-location' )
)
);
Next, register the business post type. The important bit to note here is the inclusion of the %location%
rewrite tag in the slug. We’ll use that to replace with the location term in the post_type_link
function:
register_post_type(
'business',
array(
'label' => 'Business',
'public' => true,
'rewrite' => array( 'slug' => 'business/%location%' ),
'hierarchical' => false
)
);
Now the function to swap in the location term:
function wpa_business_permalinks( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) && $post->post_type == 'business' ){
$terms = wp_get_object_terms( $post->ID, 'location' );
if( $terms ){
return str_replace( '%location%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_business_permalinks', 1, 2 );