Convert Taxonomy Options to Term Meta

WordPress 4.4 introduced Taxonomy Term Meta. Until this version, meta had to be stored as an Option. Most tutorials would tell you to give it a prefix followed by the ‘term_id’ so you can grab the data easily later. I already had a site with lots of populated meta. What I needed was a conversion script to move meta from an Option into real Term Meta.

I found a couple of interesting quirks with Term Meta while converting my site.

The first is that if you run get_term_meta( $term->term_id ) it will present you with an array of arrays. The value is stored as the first key of these sub-arrays. Where you might have had $term_meta[‘my_key’] for your option, you now need $term_meta[‘my_key’][0]. If the value returned is an array, it will need to be unserialized. This only applies if you want all Term Meta for a taxonomy. If you use get_term_meta( $term->term_id, ‘my_key’, true ) it will automatically perform both these tasks to return a single meta key.

Another difference shows itself when saving values. An Option will overwrite the value (array) in most cases. However the update function for Term Meta will only update individual meta keys. You need to iterate through and store them individually. However this is no bueno when using checkboxes. If the checkbox is unchecked, it will not be present in the postdata. Below is my generic save function for Term Meta, it will delete a value if it was stored previously but is no longer available.

When you’re all finished converting and everything is sweet. You’ll probably want to clean up your options table. Use this function at your own risk.