One challenge in WordPress is saving meta data on a taxonomy. For instance imagine you want to save additional data on a category or tag. Currently there is no wp_termmeta database table to store taxonomy meta data. In this tutorial I’m going to show you how to save a single ID against every category in WordPress. I’m going to save that meta data (the ID in this case) as a single array of options in the WordPress options table.
First we need to add a form field to the Edit Category screen. To do this we’ll use the edit_category_form_fields action hook available in WordPress:
<?php
add_action ( 'edit_category_form_fields', 'tme_cat_featured');
function tme_cat_featured( $tag ) {
//check for existing featured ID
$cat_featured = get_option( 'category_featured' );
$featured_id = '';
if ( is_array( $cat_featured ) && array_key_exists( $tag->term_id, $cat_featured ) ) {
$featured_id = $cat_featured[$tag->term_id] ;
}
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="category_featured"><?php _e('Featured Post ID') ?></label></th>
<td>
<input type="text" name="category_featured" id="category_featured" size="3" style="width:5%;" value="<?php echo $featured_id; ?>"><br />
<span class="description">The post ID that will be the featured post when viewing this category.</span>
</td>
</tr>
<?php
}
?>
The above code will add a single text field (Featured Post ID) to the Edit Category screen as shown in the screenshot below:
Now that we’ve added a text field to our Edit Category page we need to save the input to our option array. To capture the ID when a category is updated we’ll use the edited_category action hook like so:
<?php
add_action ( 'edited_category', 'tme_save_featured');
function tme_save_featured( $term_id ) {
if ( isset( $_POST['category_featured'] ) ) {
//load existing category featured option
$current_featured = get_option( 'category_featured' );
//set featured post ID to proper category ID in options array
$current_featured[$term_id] = intval( $_POST['category_featured'] );
//save the option array
update_option( 'category_featured', $current_featured );
}
}
?>
As you can see we are saving the Category ID and Featured Post ID as a single associative array option value in WordPress named category_featured. As you add Featured Post ID values to each of your categories they will be added to this array and saved in WordPress. One thing to consider when using this method is scalability. If you plan on storing thousands of meta data values for your taxonomies this isn’t the method for you.
I packaged this example into a stand alone plugin so you can easily install on your WordPress website and test it out: Download the Taxonomy Meta Data plugin example.