How can I create custom fields for taxonomies on WordPress? (PHP, Instruction 2023)

Marc Wag­ner

Janu­ary 27, 2023

6 min read|

Just like for Post Types, you can also crea­te cus­tom fields for your Word­Press taxo­no­mies. The values can then be stored in the term meta­da­ta. How the who­le thing works, I show you in this tuto­ri­al. I’ll also show you how to extend the admin table of your taxo­no­my to dis­play your values direct­ly. Final­ly, we add a sort­ing func­tion.

Create, edit and save custom fields for WordPress taxonomies #

To extend your taxo­no­mies, you need the fol­lo­wing action hooks:

  • Crea­te Terms: {$taxonomy}_add_form_fields
  • Edit Terms: {$taxonomy}_edit_form_fields
  • Save terms: created_{$taxonomy} & edited_{$taxonomy}

{$taxonomy}_add_form_fields

First, we crea­te an input for the field (we’ll call it “sort”). It is sup­po­sed to store a num­ber that can be used to sort terms, for exam­p­le. So that we can spe­ci­fy the field for our terms direct­ly when we crea­te them, we add the fol­lo­wing PHP snip­pet:

/**
 * Taxonomie: book
 */
function add_form_field_to_taxonomy_book(string $taxonomy): void{
  // add a nonce for security
  wp_nonce_field( 'book_meta_new', 'book_meta_new_nonce' );
  ?>
    <tr class="form-field">
    	<th>
    		<lable for="sort"><?php _e('Sort', 'my_domain'); ?></lable>
      	</th>
      	<td>
      		<input name="sort" id="sort" type="number" value="<?php echo esc_attr($sort); ?>"/>
      		<p class="description"><?php _e('Enter the position within the menu. Negativ values are allowed.', 'my_domain'); ?></p>
        </td>
     </tr>
  <?php
}

add_action('book_add_form_fields', 'add_form_field_to_taxonomy_book', 10, 1);

Now we have a field for ente­ring the sort. Here’s an image of how it might look in your Word­Press backend:

image 18
Added new field (sort) to a taxo­no­my (book).

{$taxonomy}_edit_form_fields

Next, we need to make sure that we can edit the terms and thus our field. After all, we would cer­tain­ly like to chan­ge the value at some point. In order for us to suc­ceed, we need to add one more func­tion:

public function edit_form_field_for_taxonomy_book(\WP_Term $term, string $taxonomy): void
{
  	$sort = get_term_meta($term->term_id, 'sort', true);

  	// add a nonce for security
  	wp_nonce_field( 'book_meta_edit', 'book_meta_edit_nonce' );
  	?>
    	<tr class="form-field">
    		<th>
    			<label for="sort"><?php _e('Sort', 'f12_table'); ?></label>
      		</th>
      		<td>
      			<input name="sort" id="sort" type="number" value="<?php echo esc_attr($sort); ?>"/>
      			<p class="description"><?php _e('Enter the position within the menu. Negativ values are allowed.', 'f12_table'); ?></p>
      		</td>
    	</tr>
	<?php
}

add_action('book_edit_form_fields', 'edit_form_field_for_taxonomy_book', 10, 2);

After the instal­la­ti­on, we are also final­ly shown a field for chan­ging our value when editing the Word­Press term. Here is an exam­p­le of what this loo­ked like in our case:

image 19
Editing our new field (sort) for the taxo­no­my (book)

created_{$taxonomy} & edited_{$taxonomy}

Final­ly, of cour­se, we need to make sure that our value is stored in the data­ba­se. The fol­lo­wing excerpt helps us here:

public function save(int $term_id)
{
  if(!isset($_POST['sort'])){
    return;
  }
  
  if(!isset($_POST['book_meta_new_nonce']) && !isset($_POST['book_meta_edit_nonce'])){
    return; 
  }
  
  if(!wp_verifiy_nonce($_POST['book_meta_new_nonce'],'book_meta_new') && !wp_verify_nonce($_POST['book_meta_edit_nonce'], 'book_meta_edit')){
    return;
  }
  
  update_term_meta($term_id, 'sort', (int)($_POST['sort']));
}

add_action('created_book', 'save_book_meta', 10, 1);
add_action('edited_book', 'save_book_meta', 10, 1)

That’s it — we have com­ple­ted all the steps to crea­te a new field, edit it and save it to the data­ba­se.

Output term metadata with a WordPress shortcode #

To out­put the data now, we crea­te a short­code. We can then place this on Word­Press pages and posts as we see fit. Here is a PHP snip­pet to query a field from your term. It does not even have to be a term from the taxo­no­my ‘book’.

/**
 * Add shortcode [book_metafield term_id=123 meta_key="sort"]
 * @return string
 */
function render_book_metafield($args, $content = ''): string{
  // parse the $args
  $args = shortcode_atts(['term_id' => 0,'meta_key' => 'sort'], $args, 'book_metafield');
  
  $value = get_term_meta($args['term_id'], 'sort', true);
  
  if(!$value){
    return 'Term not found'; 
  }
  return value;
}

add_shortcode('book_metafield', 'render_book_metafield');

The call is then made like this: [book_metafield term_id=“123” meta_key=“sort”]

Extend the Taxonomy Admin table with a new column #

You can also expand the table of your taxo­no­my to dis­play the value of the field direct­ly in the over­view. For this you need the fol­lo­wing Word­Press fil­ter and action hooks:

  • Add column: manage_edit-{$taxonomy}_columns
  • Add con­tent: manage_{$taxonomy}_custom_column
  • Make sor­ta­ble: manage_edit-{$taxonomy}_sortable_column

manage_edit-{$taxonomy}_columns

First, we tell Word­Press that we want to dis­play ano­ther column for our Taxo­no­my. For this we need to insert the fol­lo­wing PHP snip­pet:

/**
 * Add new column to taxonomy book
*/
public function add_column_for_taxonomy_book(array $columns): array
{
  $columns['sort'] = __('Sort', 'my_domain');
  return $columns;
}

// Filter: manage_edit-{$taxonomy}_columns
add_filter('manage_edit-book_columns', 'add_column_for_taxonomy_book', 10, 1)

manage_{$taxonomy}_custom_column

Now we need to expand the out­put of each line to show our value.

/**
 * Show content of term meta.
 */
public function add_content_for_taxonomy_book(string $content, string $column_name, int $term_id):void{
  // Skip if this is not our column
  if($column_name != 'sort'){
     return; 
  }
  
  $sort = get_term_meta($term_id, 'sort', true);
  
  // Skip if term or field does not exist
  if(!$sort){
     return; 
  }
  
  echo esc_attr($sort);
}

// Action: manage_{$taxonomy}_custom_column
add_action('manage_book_custom_column', 'add_content_for_taxonomy_book', 10, 3);

That’s about it. Now both the column and the row are out­put with our con­tents.

image 20
Added new column (sort) to the taxo­no­my (book).

manage_edit-{$taxonomy}_sortable_columns

Final­ly, we extend the admin table so that we can sort by our field. For this we only need the fol­lo­wing PHP snip­pet:

public function make_book_sortable(array $columns): array
{
  // Add or remove columns here. If you remove them, it
  // will remove the sort function.
  $columns['sort'] = __('Sort', 'my_domain');

  return $columns;
}

add_filter('manage_edit-book_sortable_columns', 'make_book_sortable', 10, 1);

After inser­ting, you can sort the terms by the new values in ascen­ding and des­cen­ding order by cli­cking on the column name.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar