Custom fields to taxonomy

Can I add some custom fields to specific taxonomy so when ever I call that taxonomy, custom fields attached to that taxonomy should also appear.

Related posts

Leave a Reply

2 comments

  1. You can hook into the edit form field action of that specific taxonomy.

    If you look in /wp-admin/edit-tag-form.php there are hooks for every taxonomy.
    Starting at Line 69:

            if ( 'category' == $taxonomy )
            do_action('edit_category_form_fields', $tag);
        elseif ( 'link_category' == $taxonomy )
            do_action('edit_link_category_form_fields', $tag);
        else
            do_action('edit_tag_form_fields', $tag);
    
        do_action($taxonomy . '_edit_form_fields', $tag, $taxonomy);
    

    So for a custom taxonomy, it would be $taxonomy_edit_form_fields with $taxonomy being the taxonomies name. So you would add the hook, within the function, add your form fields. Then you also need to hook into the ‘edit_term’ action and if your form fields aren’t empty then save it as an option using update_option().

    This won’t allow you to just “call the taxonomy” and have them already attached to the object, but you can loop through your terms once you get them and get the option associated with that term very easily.

  2. I developed a small script that simplifies the process of adding custom fields to taxonomies (both core & custom), and optionally lets you add columns to the terms table for each field. The script is called amarkal-taxonomy, and is part of the Amarkal WordPress framework.

    Using amarkal-taxonomy, adding a custom field simplifies to:

    // Add a text field to the 'category' taxonomy 'add' & 'edit' forms:
    amarkal_taxonomy_add_field('category', 'cat_icon', array(
        'type'        => 'text',
        'label'       => 'Icon',
        'description' => 'The category's icon',
        'table'       => array(
            'show'      => true,  // Add a column to the terms table
            'sortable'  => true   // Make that column sortable
        )
    ));
    
    // Then you can retrieve the data using:
    $icon = get_term_meta( $term_id, 'cat_icon', true );
    

    You can change 'category' to whatever your taxonomy name is.