Wordpress - Add custom taxonomy fields when creating a new taxonomy
Solved!
add_action( 'create_category', 'save_extra_taxonomy_fields', 10, 2 );
Props to the Category Meta plugin. I downloaded various category meta plugins from the WP repo, and this one has the ability to add the meta data on the Add New screen. I dug through the code and found the elusive create_{term} hook.
I think the tutorial you referenced was great and I've based this code off it. It stores the metas for taxonomy menu_category
on the add and edit forms for that taxonomy, and displays it in the edit form. The options table entry would be taxomomy_24_metas
for the term id 24.
add_action('menu_category_edit_form_fields','menu_category_edit_form_fields');
add_action('menu_category_add_form_fields','menu_category_edit_form_fields');
add_action('edited_menu_category', 'menu_category_save_form_fields', 10, 2);
add_action('created_menu_category', 'menu_category_save_form_fields', 10, 2);
function menu_category_save_form_fields($term_id) {
$meta_name = 'order';
if ( isset( $_POST[$meta_name] ) ) {
$meta_value = $_POST[$meta_name];
// This is an associative array with keys and values:
// $term_metas = Array($meta_name => $meta_value, ...)
$term_metas = get_option("taxonomy_{$term_id}_metas");
if (!is_array($term_metas)) {
$term_metas = Array();
}
// Save the meta value
$term_metas[$meta_name] = $meta_value;
update_option( "taxonomy_{$term_id}_metas", $term_metas );
}
}
function menu_category_edit_form_fields ($term_obj) {
// Read in the order from the options db
$term_id = $term_obj->term_id;
$term_metas = get_option("taxonomy_{$term_id}_metas");
if ( isset($term_metas['order']) ) {
$order = $term_metas['order'];
} else {
$order = '0';
}
?>
<tr class="form-field">
<th valign="top" scope="row">
<label for="order"><?php _e('Category Order', ''); ?></label>
</th>
<td>
<input type="text" id="order" name="order" value="<?php echo $order; ?>"/>
</td>
</tr>
<?php
}
You can add custom field to the add new term page screen through following hooks:
- {taxonomy_name}_add_form_fields
- {taxonomy_name}_edit_form_fields
- edited_{taxonomy_name}
- create_{taxonomy_name}