Custom Taxonomies

Add Custom Meta To Taxonomies

In this tutorial we are going to learn how we can add additional data to your taxonomies. WordPress comes with the ability to add meta data onto both the posts and user objects. These are stored in separate tables such as the wp_postmeta and wp_usermeta tables. Both of these tables use a key and value pair columns to store the different data just like in the wp_options table.

There is no default way of adding additional information to your taxonomies, such as images, a further description or any other attributes you want to attach to the taxonomy.

Creating A Class For Custom Meta

The following tutorial will create a PHP class that will add a couple of new fields on the taxonomy page and on the save event it will take these form values and add them into the wp_options table.

Because we are creating a class we are able to include this into our theme functions.php or add the plugin comments to the top of the file and include this as a plugin.

First we create the class and create the constructor for the code. Inside the constructor are the actions that we are going to add to run the other methods in the class.

The first action is going to run on the init action and will register the taxonomy which we can use for the additional fields.

The next actions are going to add the HTML fields for both the add and edit forms. You can add the forms to either the default category form or to brand new custom taxonomy.

// Add fields to category form
add_action( 'category_add_form_fields', 'add_new_custom_fields');

// Add fields to category edit form
add_action( 'category_edit_form_fields', 'add_edit_custom_fields');

// Add fields on custom taxonomies
add_action( '{custom-taxonomy-name}_add_form_fields', 'add_new_custom_fields');
add_action( '{custom-taxonomy-name}_edit_form_fields', 'add_edit_custom_fields');

The next actions we are going to add are going to save the data to the wp_options table, for this we are going to use the following actions which can be run on the default category taxonomy or to custom taxonomies.

// Add fields to category form
add_action( 'create_category', 'save_custom_taxonomy_meta');

// Add fields to category edit form
add_action( 'edited_category', 'save_custom_taxonomy_meta');

// Add fields on custom taxonomies
add_action( 'create_{custom-taxonomy-name}', 'save_custom_taxonomy_meta');
add_action( 'edited_{custom-taxonomy-name}', 'save_custom_taxonomy_meta');

Full Constructor Code

/**
 * Test Taxonomy Custom Meta
 */
class Test_Taxonomy_Custom_Meta
{
    public function __construct()
    {
        add_action( 'init', array($this, 'register_custom_fields_taxonomy'));

        /**
         * Add new category data fields
         */
        add_action( 'custom-taxonomy_add_form_fields', array($this, 'add_new_custom_fields'));

        /**
         * Edit category data fields
         */
        add_action( 'custom-taxonomy_edit_form_fields', array($this, 'add_edit_custom_fields'));

        /**
         * Save the category data
         */
        add_action( 'edited_custom-taxonomy', array($this, 'save_custom_taxonomy_meta') );
        add_action( 'create_custom-taxonomy', array($this, 'save_custom_taxonomy_meta') );
    }
}

Register The Taxonomy

The following code is the method used to create the custom taxonomy custom-taxonomy.

/**
     * Register the social update
     */
    public function register_custom_fields_taxonomy()
    {
        $labels = array(
            'name'				    => __( 'Custom Taxonomy' ),
            'singular_name'			=> __( 'Custom Taxonomy' ),
            'search_items'			=> __( 'Search Custom Taxonomy' ),
            'popular_items'			=> __( 'Popular Custom Taxonomy' ),
            'all_items'			    => __( 'All Custom Taxonomy' ),
            'parent_item'			=> __( 'Parent Custom Taxonomy' ),
            'parent_item_colon'		=> __( 'Parent Custom Taxonomy'  ),
            'edit_item'			    => __( 'Edit Custom Taxonomy' ),
            'update_item'			=> __( 'Update Custom Taxonomy'),
            'add_new_item'			=> __( 'Add New Custom Taxonomy'),
            'new_item_name'			=> __( 'New single Custom Taxonomy'),
            'add_or_remove_items'	=> __( 'Add or remove Custom Taxonomy'),
            'choose_from_most_used'	=> __( 'Choose from most used Custom Taxonomy'),
            'menu_name'			    => __( 'Custom Taxonomy'),
        );

        register_taxonomy(
            'custom-taxonomy',
            'post',
            array(
                'labels'            => $labels,
                'public'            => false,
                'show_in_nav_menus'	=> true,
                'hierarchical'		=> true,
                'show_ui'		    => true,
                'query_var'		    => true,
                'rewrite'		    => true,
                'show_admin_column' => true
            )
        );
    }

Add Fields To New Taxonomy Form

The following code is the method we will use to add the form fields to the new taxonomy form. The action will run at the bottom of the form where we add the HTML for the taxonomy fields, in this example we are simply adding 4 new fields for term meta.

/**
 * Add the new custom fields
 */
public function add_new_custom_fields( )
{
    ?>
    <div class="form-field">
        <label for="term_meta[field1]"><?php _e( 'Field 1' ); ?></label>
        <input type="text" name="term_meta[field1]" id="term_meta[field1]" value="">
    </div>

    <div class="form-field">
        <label for="term_meta[field2]"><?php _e( 'Field 2' ); ?></label>
        <input type="text" name="term_meta[field2]" id="term_meta[field2]" value="">
    </div>

    <div class="form-field">
        <label for="term_meta[field3]"><?php _e( 'Field 3' ); ?></label>
        <input type="text" name="term_meta[field3]" id="term_meta[field3]" value="">
    </div>

    <div class="form-field">
        <label for="term_meta[field4]"><?php _e( 'Field 4' ); ?></label>
        <input type="text" name="term_meta[field4]" id="term_meta[field4]" value="">
    </div>
    <?php
}

Add Fields To Edit Taxonomy Form

The following code is used to add HTML to the bottom of the edit taxonomy form. First we need to check if there is any existing data in the options table for the term, for this we use the get_option() function and lookup the data for 'custom_taxonomy_meta_' . $term->term_id.

The edit form method will come with a parameter of the term object we are editing so we can use this to get the term id.

If there is existing data for the term then we can add this form fields to edit the existing data.

/**
 * Add the edit custom fields
 */
public function add_edit_custom_fields( $term )
{
    $termMeta = get_option( 'custom_taxonomy_meta_' . $term->term_id );
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="term_meta[field1]"><?php _e( 'Field 1' ); ?></label></th>
        <td>
            <input type="text" name="term_meta[field1]" id="term_meta[field1]" value="<?php if(!empty($termMeta['field1'])){ esc_attr_e($termMeta['field1']); } ?>">
        </td>
    </tr>

    <tr class="form-field">
        <th scope="row" valign="top"><label for="term_meta[field2]"><?php _e( 'Field 2' ); ?></label></th>
        <td>
            <input type="text" name="term_meta[field2]" id="term_meta[field2]" value="<?php if(!empty($termMeta['field2'])){ esc_attr_e($termMeta['field2']); } ?>">
        </td>
    </tr>

    <tr class="form-field">
        <th scope="row" valign="top"><label for="term_meta[field3]"><?php _e( 'Field 3' ); ?></label></th>
        <td>
            <input type="text" name="term_meta[field3]" id="term_meta[field3]" value="<?php if(!empty($termMeta['field3'])){ esc_attr_e($termMeta['field3']); } ?>">
        </td>
    </tr>

    <tr class="form-field">
        <th scope="row" valign="top"><label for="term_meta[field4]"><?php _e( 'Field 4' ); ?></label></th>
        <td>
            <input type="text" name="term_meta[field4]" id="term_meta[field4]" value="<?php if(!empty($termMeta['field4'])){ esc_attr_e($termMeta['field4']); } ?>">
        </td>
    </tr>
    <?php
}

Save The Taxonomy Data

The final method we need to create is the method that will save the taxonomy meta information inside the wp_options table using the update_option() function.

The action will add a parameter for the term ID that we have just created or are currently editing. First we get the existing values stored for the term meta, next we can loop through the content inside the $_POST data for the term meta and update the $term_meta data array so we can store this in the wp_options table using the function update_option().

/**
 * Save the taxonomy custom meta
 */
public function save_social_account_custom_meta($termId)
{
    if ( !empty( $_POST['term_meta'] ) )
    {
        $term_meta = get_option( 'custom_taxonomy_meta_' . $termId );

        foreach ( $_POST['term_meta'] as $key => $val )
        {
            $term_meta[$key] = sanitize_text_field($val);
        }

        update_option( 'custom_taxonomy_meta_' . $termId, $term_meta );
    }
}

If you add all these methods to the class then this is all the code you need to add extra form fields to the taxonomy to use else where in your theme. To get this data for the taxonomy elsewhere in your theme or a plugin we just have to use the get_option() with the term ID.

$termMeta = get_option( 'custom_taxonomy_meta_' . $termId );
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days

Comments

  1. hexcross says:

    Good solution! Thanks very much man 🙂

  2. James says:

    Hi, I seem to be having trouble displaying these meta fields on an archive and single template of the custom post type I've created. I used the get_option() with the term ID to no avail. Is there a specific way it needs to be called? Like within the loop?