close

Shelley Bassett

Menu

Close

Save Metadata to a Custom Taxonomy


August 20, 2018

After making custom post types and custom taxonomies, it’s often useful to add custom meta fields so that extra variables can be added to help define the taxonomy. It’s easy to save metadata to a custom taxonomy, and can provide some great functionality. Having metadata in taxonomies is also handy for displaying information on the […]

Its easy to save metadata to a custom taxonomy and provides some much needed flexibility to WordPress categories

After making custom post types and custom taxonomies, it’s often useful to add custom meta fields so that extra variables can be added to help define the taxonomy. It’s easy to save metadata to a custom taxonomy, and can provide some great functionality.

Having metadata in taxonomies is also handy for displaying information on the front end. Taxonomies have very limited space for storing information, and by default only allow for the title, slug, parent category and description. Not so useful if you require something like a custom excerpt.

How to save metadata to a custom taxonomy

Adding metadata to a category or custom taxonomy is a bit different from posts. Instead of creating a new  meta box, a new row is added to the existing table. The following code is to add an excerpt field to a category. This is the new row to add our custom meta in when editing the category.

After changing the category form to accept the new meta, it needs to be saved in the database. This step allows the metadata to be called from any page on the site.

This save function has two actions added. This is because of the way that categories and taxonomies are written to the database. One function is for creating a category, and another for if or when it is updated. These functions are  add_action( 'edited_category', 'cat_excerpt_save_meta', 10, 2 ); and  add_action( 'create_category', 'cat_excerpt_save_meta', 10, 2 ); .

It’s also useful to know that the table row added in the first step can take any input field, just like the custom metadata in posts. This example uses  <input type="text"></input> as this fits the requirements for an excerpt.

Calling the new metadata

Calling the custom metadata from the category is just as easy as calling custom metadata from a post. Use the correct meta key and the category ID to retrieve it from the database. Then just add it to the page template or function and it’s good to go!

Leave a comment

Advertisement

Leave a Message | No comments yet

Leave a Reply

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