Custom post types related to same custom post type?

I suspect what you’re trying to do is implement related posts, and you’re using post meta to indicate which posts are related to the current post.

So if I have a handbag, and there are 5 related products, the handbag product has post meta containing the IDs of those 5 products.

While this sort of works, it doesn’t scale, and it isn’t performant.

Instead use a custom taxonomy. Do this:

  • hook into product post creation and deletion
  • When a product is saved/delete, create and delete a term in the new taxonomy whose slug is something like “X” where X is the ID of your product. Give the nice pretty name the posts title so users know what they’re selecting
  • Now when in a product post, to set related posts, check the posts that’re related in your new related products taxonomy
  • On the frontend, to figure out which posts are related, use wp_get_object_terms to get all the terms that product has in the related posts taxonomy.
  • Loop over each term, extract the slug, which is also the ID of the related product, and pass it into get_post() to get a post object
  • Display this post object as you normally would

As a bonus, if your product is related to X, the might be other products related to X, therefore those are probably related too.

The downside of this is you need to manually set for each product what’s related. However, you can get around this using a heuristic:

If 2 products are in the same sub category, they’re probably related

So to show all related products, just show the products that share the deepest product category. There are questions on how to find the deepest level categories on the site