Add Custom Field To Category Settings Pages

I ran across something today where I wanted to add a checkbox to a WooCommerce product category page. Just a simple checkbox.

I wanted to be able to use that to change how the front end of the website handled products in that category. It worked great, btw – new plugin coming soon!

The below code will work for any category taxonomy type settings page. There’s many reasons a website might have a custom taxonomy outside of the regular posts categories. The most common would be WooCommerce and the products categories – “product_cat” is their name in WordPress. If you have a different custom taxonomy, you would use that name. If you’re unsure where to find that name, you can grab it from the URL of the category settings page:

Once you have that name, just change the appearance of “product_cat” with whatever the name of your taxonomy is. If you just want to add to posts categories, use “category”

You can add pretty much any type of field or option too if you’re up for coding it. The below example can take any HTML, you could easily just change the HTML sections to have text, textareas, selects, checkboxes etc.

Add an option field to the category settings pages:

// Add to new term page
function add_category_meta( $taxonomy ) { 
  //html code here
}
add_action( 'product_cat_add_form_fields', 'add_category_meta', 99, 2 );

// Add to edit term page
function edit_category_meta( $term, $taxonomy ) {
  //html code here
}
add_action( 'product_cat_edit_form_fields', 'edit_category_meta', 99, 2 );

// Save it
function save_category_meta( $term_id, $tag_id ) {
  $setting = sanitize_key($_POST[ 'field_name_from_input_field' ]);
  if ( !empty( $setting ) ) {
    update_term_meta( $term_id, 'field_name_from_input_field', 'yes' );
  } else {
    update_term_meta( $term_id, 'field_name_from_input_field', '' );
  }
}
add_action( 'created_product_cat', 'save_category_meta', 10, 2 );
add_action( 'edited_product_cat', 'save_category_meta', 10, 2 );

Leave a Reply

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