I suspect the answer might be, get ready to write some SQL but I'm going to ask anyway.

I have a situation where I am pulling data from an outside source and storing it in a custom post type. For the main, this looks like it will work very well. However, there is a slight bump in the road.

The data comes with what are called stances. They exist as key-value pairs where key and value could be anything. Given that I store other data in the meta already, what I was hoping for was something like tags but in pairs. A taxonomy that works exactly like tags in most respects but has two values.

I toyed with converting the values into $tag = "{$key}|{$value}"; but I can see that getting messy and bloated really fast.

The current solution puts the entire array into a single meta. It works but it is not great for "select all posts of type X that agree foo is bar".

Which brings me to ask if a more complex two-factor taxonomy is even possible?


When importing you could create a taxonomy for each unique stance key, then add the value as a term to the taxonomy for that key, then assign that term to the post.

I'd suggest something like:

  1. Store the stance keys somewhere in the database (probably as options), making sure that you don't have duplicates. Depending on how many you have, this could probably just be a single value with a serialised array.
  2. On the init hook, read the list of keys with get_option(), and register a taxonomy for each one with register_taxonomy().
  3. When importing, save any new keys to the database, and immediately run register_taxonomy() for them so that the taxonomy is registered for the rest of the process.
  4. For the values, add them as terms to the taxonomy using wp_insert_term(), but only after checking that value doesn't already exist with get_term_by().
  5. Once the taxonomy has been registered, and the term for the value has been inserted or found, assign the term to the post using wp_set_post_terms().

If you do that then you can easily filter posts based on these values with a taxonomy query. This will be faster than attempting to filter using post meta.

  • There is a certain genius to this. Could have a lot of taxonomies but that's not the end of the world. – Matthew Brown aka Lord Matt Jun 12 '19 at 16:25
  • I further realised that I could (and maybe should) limit stance values to one of five possibles. If the possibles were the tax, there would be only five. Inside out, but should work. – Matthew Brown aka Lord Matt Aug 4 '19 at 1:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.