Using WordPress ‘ajax_term_search_results’ PHP filter

The ajax_term_search_results WordPress PHP filter allows you to modify the search results returned by an Ajax term search.

Usage

add_filter('ajax_term_search_results', 'your_custom_function', 10, 3);

function your_custom_function($results, $taxonomy_object, $search) {
    // your custom code here
    return $results;
}

Parameters

  • $results (string[]): Array of term names.
  • $taxonomy_object (WP_Taxonomy): The taxonomy object.
  • $search (string): The search term.

More information

See WordPress Developer Resources: ajax_term_search_results

Examples

Add a prefix to term names

In this example, we add a prefix to each term name in the search results.

function add_prefix_to_term_names($results, $taxonomy_object, $search) {
    $prefixed_results = array_map(function ($term) {
        return 'Prefix: ' . $term;
    }, $results);

    return $prefixed_results;
}
add_filter('ajax_term_search_results', 'add_prefix_to_term_names', 10, 3);

Filter out specific terms

In this example, we remove terms containing the word “example” from the search results.

function remove_example_terms($results, $taxonomy_object, $search) {
    return array_filter($results, function ($term) {
        return strpos($term, 'example') === false;
    });
}
add_filter('ajax_term_search_results', 'remove_example_terms', 10, 3);

Sort terms by length

In this example, we sort the terms in the search results by their length.

function sort_terms_by_length($results, $taxonomy_object, $search) {
    usort($results, function ($a, $b) {
        return strlen($a) - strlen($b);
    });

    return $results;
}
add_filter('ajax_term_search_results', 'sort_terms_by_length', 10, 3);

Limit the number of results

In this example, we limit the number of terms in the search results to a maximum of 5.

function limit_term_results($results, $taxonomy_object, $search) {
    return array_slice($results, 0, 5);
}
add_filter('ajax_term_search_results', 'limit_term_results', 10, 3);

Append term count to term names

In this example, we append the term count to each term name in the search results.

function append_term_count($results, $taxonomy_object, $search) {
    global $wpdb;

    $updated_results = [];

    foreach ($results as $term_name) {
        $term = get_term_by('name', $term_name, $taxonomy_object->name);

        if ($term) {
            $count = $term->count;
            $updated_results[] = $term_name . ' (' . $count . ')';
        }
    }

    return $updated_results;
}
add_filter('ajax_term_search_results', 'append_term_count', 10, 3);