As a WordPress developer, some times we need to add fields to custom taxonomy. So, in this post we are going through the code snippet for adding field to taxonomy. Let have a look,

Here we are taking the taxonomy named `product_cat` which is the woocommerce product category and we are adding the field to feature product categories in woocommerce

/** Add Custom Field To Category Form */
add_action( 'product_cat_add_form_fields', 'product_cat_taxonomy_custom_fields', 10, 2 );
add_action( 'product_cat_edit_form_fields', 'product_cat_taxonomy_custom_fields', 10, 2 );
function product_cat_taxonomy_custom_fields($tag) {  
   // Check for existing taxonomy meta for the term you're editing  
   $t_id = $tag->term_id; // Get the ID of the term you're editing  
   $term_meta = get_option( "product_cat_featured_$t_id" ); // Do the check  
?>  
  
<tr class="form-field">  
    <th scope="row" valign="top">  
        <label for="presenter_id"><?php _e('Featured'); ?></label>  
    </th>  
    <td>  
      <select name="featured" id="featured" class="postform">
	<option value="0">Select</option>
	<option <?= $term_meta=='Yes'?'selected':'' ?>   value="Yes">Yes</option>
	<option <?= $term_meta=='No'?'selected':'' ?>   value="No">No</option> 
</select> 
    </td>  
</tr>  
  
<?php  
}  

The above code allows us to add out html code to the add new page and edit taxonomy page
we can modify to this to any html you need.
Add Fields To Custom Taxonomy
The only thing to note here is to keep the name of the field we created and we need that to save the data to the database

Now the second part of the code is to save the data to the database

/** Save Custom Field Of Category Form */
add_action( 'created_product_cat', 'product_cat_form_custom_field_save', 10, 2 );	
add_action( 'edited_product_cat', 'product_cat_form_custom_field_save', 10, 2 );
 
function product_cat_form_custom_field_save( $term_id, $tt_id ) {
 
	if ( isset( $_POST['featured'] ) ) {			
		$option_name = 'product_cat_featured_' . $term_id;
		update_option( $option_name, $_POST['featured'] );
	}
}

Hope this will help you to add fields to custom taxonomy and you can easily modify this code to you taxonomy
the only thing you need to change is `product_cat` and the name of the field

Leave a Reply

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