WordPress Term Meta: add_term_meta, get_term_meta, and Custom Fields for Categories

Term meta: custom fields for categories, tags and custom taxonomies

Since WordPress 4.4 terms have their own meta table, and add_term_meta(), get_term_meta(), update_term_meta() and delete_term_meta() work like their post counterparts. Before that, plugins kept term data in options with keys like category_12_image. Term meta is the place for data that belongs to the term itself: a banner image of a category, a colour of a tag, a sort order of a product category.

Problem: WooCommerce product categories need a banner image and a sort order, editable on the category screen and available in the templates.

Solution: Register the meta with register_term_meta() (WordPress 4.9.8+) including a sanitize callback, add the fields with the {taxonomy}_add_form_fields and {taxonomy}_edit_form_fields actions, save them on created_{taxonomy} and edited_{taxonomy}, and read them with get_term_meta().

Registering the meta

<?php
add_action( 'init', function () {
    register_term_meta( 'product_cat', 'ha_banner_id', array(
        'type'              => 'integer',
        'single'            => true,
        'sanitize_callback' => 'absint',
        'show_in_rest'      => true,
    ) );

    register_term_meta( 'product_cat', 'ha_sort_order', array(
        'type'              => 'integer',
        'single'            => true,
        'sanitize_callback' => 'intval',
        'show_in_rest'      => true,
    ) );
} );

With the sanitize callbacks registered, update_term_meta() cleans the values itself, wherever they come from.

The fields

The “Add new” form on the left of the list is a set of divs, the edit screen is a table, so the two need different markup:

<?php
add_action( 'product_cat_add_form_fields', function () {
    ?>
    <div class="form-field">
        <label for="ha_sort_order"><?php esc_html_e( 'Sort order', 'textdomain' ); ?></label>
        <input type="number" name="ha_sort_order" id="ha_sort_order" value="0">
    </div>
    <?php
} );

add_action( 'product_cat_edit_form_fields', function ( $term ) {
    $banner = (int) get_term_meta( $term->term_id, 'ha_banner_id', true );
    $order  = (int) get_term_meta( $term->term_id, 'ha_sort_order', true );
    ?>
    <tr class="form-field">
        <th scope="row"><label for="ha_banner_id"><?php esc_html_e( 'Banner image ID', 'textdomain' ); ?></label></th>
        <td>
            <input type="number" name="ha_banner_id" id="ha_banner_id" min="0" value="<?php echo esc_attr( $banner ); ?>">
            <?php echo $banner ? wp_get_attachment_image( $banner, 'thumbnail' ) : ''; ?>
        </td>
    </tr>
    <tr class="form-field">
        <th scope="row"><label for="ha_sort_order"><?php esc_html_e( 'Sort order', 'textdomain' ); ?></label></th>
        <td><input type="number" name="ha_sort_order" id="ha_sort_order" value="<?php echo esc_attr( $order ); ?>"></td>
    </tr>
    <?php
} );

A number field for the image ID keeps the example short; a “Choose image” button with the media library works as described in the post about wp_enqueue_media().

Saving

<?php
function ha_save_product_cat_meta( $term_id ) {
    if ( ! current_user_can( 'edit_term', $term_id ) ) {
        return;
    }

    foreach ( array( 'ha_banner_id', 'ha_sort_order' ) as $key ) {
        if ( isset( $_POST[ $key ] ) ) {
            update_term_meta( $term_id, $key, wp_unslash( $_POST[ $key ] ) ); // sanitized by register_term_meta()
        }
    }
}
add_action( 'created_product_cat', 'ha_save_product_cat_meta' );
add_action( 'edited_product_cat', 'ha_save_product_cat_meta' );

These hooks run after WordPress has checked the nonce of the term form, so no extra nonce field is needed for them. The capability check makes the function safe when terms are created in other ways, for example through the REST API.

Using the values

<?php
// On the category archive
$term = get_queried_object();

if ( $term instanceof WP_Term ) {
    $banner = (int) get_term_meta( $term->term_id, 'ha_banner_id', true );
    if ( $banner ) {
        echo wp_get_attachment_image( $banner, 'full', false, array( 'class' => 'category-banner' ) );
    }
}

// Categories ordered by the custom field
$cats = get_terms( array(
    'taxonomy'   => 'product_cat',
    'meta_key'   => 'ha_sort_order',
    'orderby'    => 'meta_value_num',
    'order'      => 'ASC',
    'hide_empty' => false,
) );

NOTE: As with post meta, ordering by meta_key drops terms that do not have the field. Give new terms a default value on creation, as the “Add new” field above does, so they all appear in sorted lists.