Using WordPress ‘register_term_meta()’ PHP function

The register_term_meta() WordPress PHP function registers a meta key for terms in a specified taxonomy.

Usage

register_term_meta( $taxonomy, $meta_key, $args )

Example:

register_term_meta( 'category', 'color', array( 'type' => 'string', 'single' => true, 'show_in_rest' => true ) );

Parameters

  • $taxonomy (string) – Taxonomy to register a meta key for. Pass an empty string to register the meta key across all existing taxonomies.
  • $meta_key (string) – The meta key to register.
  • $args (array) – Data used to describe the meta key when registered. See register_meta() for a list of supported arguments.

More information

See WordPress Developer Resources: register_term_meta()

Examples

Register color meta key for category taxonomy

Registers a ‘color’ meta key for the ‘category’ taxonomy.

add_action( 'init', 'register_category_color_meta' );

function register_category_color_meta() {
    register_term_meta( 'category', 'color', array( 'type' => 'string', 'single' => true, 'show_in_rest' => true ) );
}

Register a meta key for all taxonomies

Registers a ‘location’ meta key for all taxonomies.

add_action( 'init', 'register_location_meta_for_all_taxonomies' );

function register_location_meta_for_all_taxonomies() {
    register_term_meta( '', 'location', array( 'type' => 'string', 'single' => true, 'show_in_rest' => true ) );
}

Register a boolean meta key

Registers a ‘featured’ boolean meta key for ‘tag’ taxonomy.

add_action( 'init', 'register_featured_meta' );

function register_featured_meta() {
    register_term_meta( 'post_tag', 'featured', array( 'type' => 'boolean', 'single' => true, 'show_in_rest' => true ) );
}

Register a meta key with a custom sanitize callback

Registers a ‘phone_number’ meta key for ‘category’ taxonomy and sanitizes the input.

add_action( 'init', 'register_phone_number_meta' );

function register_phone_number_meta() {
    register_term_meta( 'category', 'phone_number', array( 'type' => 'string', 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => 'sanitize_text_field' ) );
}

Register a meta key with a default value

Registers a ‘rating’ meta key for ‘post_tag’ taxonomy with a default value of 0.

add_action( 'init', 'register_rating_meta' );

function register_rating_meta() {
    register_term_meta( 'post_tag', 'rating', array( 'type' => 'integer', 'single' => true, 'show_in_rest' => true, 'default' => 0 ) );
}