WordPress: Adding custom fields to taxonomies

How do I add a custom field to a taxonomy?

I would like to add an image path field to upload images for a single taxonomy entry. This image should be displayed in the frontend at the end. After some reading I did not find a tutorial that was not too old or completly right. Many custom functions and too many outdated WordPress hooks and functions to achieve the mentioned goal. Finally I  got the custom field working and I would like to explain the solution here.

Adding a taxonomy field

So lets start with two actions which add fields to our taxonomy forms. $taxonomyName is the name of the taxonomy you will alter. WordPress default taxonomies are called category and tag. But you can also use these functions with your custom taxonomy, using its name. The add_form_fields hook version adds the form fields when we are adding a new taxonomy term. The edit_form_fields  hook adds the form fields when we are editing a taxonomy term. [1][2]

A sample function for adding a new field can look like the following. We have to use two sepereate functions here because WordPress renders the view to add a term with a <div> structure and to edit a term with a <table> structure. We also add some magic to the _onedit function to receive the saved values from the database. To learn how to store your new values into the database you have to continue with the next section.

 Saving field values to the database

Again we need two separate action hooks for saving our fields into the database. One action for the add screen and the other for the edit screen. [2]

But we just need a single function for storing the sent values into the database using the WordPress Options API. We are creating a new options entry for each term using the termID. Further we are going to save the options for each term as an array. So we can store multiple field values in one entry, if we are expanding the taxonomy meta data.

Ressources

[1] http://wordpress.stackexchange.com/questions/689/adding-fields-to-the-category-tag-and-custom-taxonomy-edit-screen-in-the-wordpr

[2] http://php.quicoto.com/add-metadata-categories-wordpress/