The issue you are experiencing might be due to the action hook you’re using to save the term meta. The created_category
hook fires after the term is created, but it doesn’t ensure that all fields are available at that point.
To ensure that the term meta is being saved correctly even for the first category, you might want to use the create_term
or create_category
hooks. These hooks are fired after a new term or category is created in the database and all information is already available.
Here is how you might modify your code:
function mt_set_color_category_term_meta( $term_id ) {
if( isset( $_POST['_term_color'] ) && ! empty( $_POST['_term_color'] ) ) {
update_term_meta( $term_id, '_term_color', sanitize_hex_color( $_POST['_term_color'] ) );
} else {
delete_term_meta( $term_id, '_term_color' );
}
}
add_action( 'create_term', 'mt_set_color_category_term_meta' );
add_action( 'edit_term', 'mt_set_color_category_term_meta' );
You may also want to consider using the edit_term
action instead of edited_category for consistency and to ensure it works for all term types, not just categories. The edit_term
action fires after a term has been updated, and it works for any taxonomy.