Q:

Rewrite rules for using the same base slug for multiple content types

I'm not sure if this is possible or not, but here is what I'm trying to achieve. I'm using WooCommerce, and I have it setup to prepend a base slug and the product category to my product permalinks. So, my product permalinks look like this:
example.com/shop/%product_category%/%product_slug%
Now, I want to create another post type called "gemstone" that uses the shop base page in its permalinks, so they would look like this:
example.com/shop/gemstone/%gemstone_slug%
The problem is that all of the gemstone pages 404. This is because their URLs are rewritten so that "gemstone" is assumed to be the %product_category% and the %gemstone_slug% is assumed to be the %product_slug%. I'm having trouble thinking of a way around this, but URL rewriting is pretty new to me. Anyone have any thoughts?
As a bonus, another problem with the product permalinks is that their attachment pages (e.g. example.com/shop/%product_category%/%product_slug%/%attachment%) all 404 as well. For reference, I have opened a bug ticket for the attachment page issue on the WooCommerce github.

A:

Ok, the solution here turned out to be setting the correct priority on the add_action hook. Since we're all hooking into init to register our post types per the Codex, the priority will determine which register_post_type function gets called first and, by extension, the order of the generated rewrite rules.
So, I needed my "gemstone" rewrite rules to be checked before the "product" rewrite rules, so if they match, the product rules won't even be checked. It's a bit annoying that I had to use a negative value for the priority argument to achieve this because WooCommerce uses a priority of 0 for their register post type action, but that's a minor issue.
I still don't know how best to make the attachment pages work (the bonus question from above), but that is probably best left to the core WooCommerce team.

