Using WordPress ‘get_object_terms’ PHP filter

The get_object_terms WordPress PHP filter allows you to modify the terms associated with a specific object or group of objects.

Usage

add_filter('get_object_terms', 'your_custom_function', 10, 4);
function your_custom_function($terms, $object_ids, $taxonomies, $args) {
    // your custom code here
    return $terms;
}

Parameters

  • $terms (WP_Term[]|int[]|string[]|string): An array of terms, term count, or a single term as a numeric string.
  • $object_ids (int[]): An array of object IDs for which terms were retrieved.
  • $taxonomies (string[]): An array of taxonomy names from which terms were retrieved.
  • $args (array): An array of arguments for retrieving terms for the given object(s). See wp_get_object_terms() for details.

More information

See WordPress Developer Resources: get_object_terms

Examples

Exclude a specific term

Exclude the term with ID 5 from the terms list.

add_filter('get_object_terms', 'exclude_specific_term', 10, 4);
function exclude_specific_term($terms, $object_ids, $taxonomies, $args) {
    $exclude_term_id = 5;
    $terms = array_filter($terms, function($term) use ($exclude_term_id) {
        return $term->term_id != $exclude_term_id;
    });

    return $terms;
}

Change the term order

Sort terms alphabetically by name.

add_filter('get_object_terms', 'sort_terms_alphabetically', 10, 4);
function sort_terms_alphabetically($terms, $object_ids, $taxonomies, $args) {
    usort($terms, function($a, $b) {
        return strcmp($a->name, $b->name);
    });

    return $terms;
}

Add a custom prefix to term names

Add a custom prefix to each term name.

add_filter('get_object_terms', 'add_custom_prefix_to_term_names', 10, 4);
function add_custom_prefix_to_term_names($terms, $object_ids, $taxonomies, $args) {
    $prefix = 'Custom Prefix: ';
    foreach ($terms as $term) {
        $term->name = $prefix . $term->name;
    }

    return $terms;
}

Filter terms by custom taxonomy

Keep only terms from a custom taxonomy named “my_custom_taxonomy”.

add_filter('get_object_terms', 'filter_terms_by_custom_taxonomy', 10, 4);
function filter_terms_by_custom_taxonomy($terms, $object_ids, $taxonomies, $args) {
    $custom_taxonomy = 'my_custom_taxonomy';
    $terms = array_filter($terms, function($term) use ($custom_taxonomy) {
        return $term->taxonomy == $custom_taxonomy;
    });

    return $terms;
}

Limit the number of terms

Limit the terms list to the first 3 terms.

add_filter('get_object_terms', 'limit_number_of_terms', 10, 4);
function limit_number_of_terms($terms, $object_ids, $taxonomies, $args) {
    $terms = array_slice($terms, 0, 3);

    return $terms;
}