The has_term_meta() WordPress PHP function retrieves all meta data, including meta IDs, for a given term ID.
Usage
$meta_data = has_term_meta( $term_id );
Input:
$term_id: Term ID (e.g. 5)
Output:
- Array of term meta data
Parameters
$term_id (int): Required. The term ID you want to retrieve meta data for.
More information
See WordPress Developer Resources: has_term_meta()
Examples
Retrieve term meta data
Retrieve all meta data for a term with ID 5.
$term_id = 5;
$term_meta_data = has_term_meta( $term_id );
// Print the term meta data
foreach ( $term_meta_data as $meta_data ) {
echo 'Meta key: ' . $meta_data['meta_key'] . ', Meta value: ' . $meta_data['meta_value'] . '<br>';
}
Check if term has a specific meta key
Check if a term with ID 5 has a meta key called ‘color’.
$term_id = 5;
$term_meta_data = has_term_meta( $term_id );
$has_color = false;
foreach ( $term_meta_data as $meta_data ) {
if ( $meta_data['meta_key'] == 'color' ) {
$has_color = true;
break;
}
}
if ( $has_color ) {
echo 'Term has color meta key';
} else {
echo 'Term does not have color meta key';
}
Count term meta keys
Count the number of meta keys for a term with ID 5.
$term_id = 5; $term_meta_data = has_term_meta( $term_id ); $count_meta_keys = count( $term_meta_data ); echo 'Term has ' . $count_meta_keys . ' meta keys';
Retrieve term meta value by meta key
Get the meta value of ‘color’ for a term with ID 5.
$term_id = 5;
$term_meta_data = has_term_meta( $term_id );
$color_value = '';
foreach ( $term_meta_data as $meta_data ) {
if ( $meta_data['meta_key'] == 'color' ) {
$color_value = $meta_data['meta_value'];
break;
}
}
echo 'Term color: ' . $color_value;
Get term meta IDs
Retrieve all meta IDs for a term with ID 5.
$term_id = 5;
$term_meta_data = has_term_meta( $term_id );
$meta_ids = array();
foreach ( $term_meta_data as $meta_data ) {
$meta_ids[] = $meta_data['meta_id'];
}
echo 'Term meta IDs: ' . implode( ', ', $meta_ids );