Rewrite rules for custom post type ‘attached’ to another custom post type

I have two custom post types: let’s call them location and topic. The location custom post type is hierarchical. All articles are ‘attached’ to a single location using post meta. If it matters, the topic post type has a custom meta box that contains a dropdown of the locations that saves using:

update_post_meta( $post->ID, 'my-prefix-location', $the_location );

I’d like the rewrite the location so that their URLs would be https://my.domain.tld/location/sub-location/sub-sub-location/topic/.

For the location, I’ve tried, while registering the post type, to use the following rewrite argument:

'rewrite' => [ 'slug' => '/', 'with_front' => false, ],

That works fine for the locations, but I cannot access any of the topics, even after manually flushing rewrite rules. If I query them with /?id=100, they redirect to /topic/slug/ ( which isn’t the URL structure I want ) but it results in a 404.

But even if I solve that problem, I have no idea how to rewrite the URLs for the topics so that they have the structure of the attached location in front.

I think I’m going to have to add_rewrite_rule() and/or add_rewrite_endpoint(). I’ve never actually used either of those functions before. Any pointers would be appreciated. Am I going about this the wrong way?

Read more here: Rewrite rules for custom post type ‘attached’ to another custom post type

Leave a Reply

Your email address will not be published. Required fields are marked *