Using WordPress ‘pre_get_terms’ PHP action

The pre_get_terms WordPress PHP action fires before terms are retrieved, allowing you to modify the query.

Usage

add_action('pre_get_terms', 'your_custom_function');
function your_custom_function($query) {
  // your custom code here
  return $query;
}

Parameters

  • $query (WP_Term_Query): Current instance of WP_Term_Query (passed by reference).

More information

See WordPress Developer Resources: pre_get_terms

Examples

Exclude a specific term from the query

Exclude a specific term (by term ID) from the terms query.

add_action('pre_get_terms', 'exclude_specific_term');
function exclude_specific_term($query) {
  $term_id_to_exclude = 42; // Replace with the term ID you want to exclude
  $query->query_vars['exclude'] = $term_id_to_exclude;
  return $query;
}

Limit the number of terms returned

Limit the number of terms returned by the query.

add_action('pre_get_terms', 'limit_number_of_terms');
function limit_number_of_terms($query) {
  $query->query_vars['number'] = 5; // Limit the number of terms to 5
  return $query;
}

Order terms by title

Order the terms returned by the query alphabetically by their title.

add_action('pre_get_terms', 'order_terms_by_title');
function order_terms_by_title($query) {
  $query->query_vars['orderby'] = 'name';
  $query->query_vars['order'] = 'ASC';
  return $query;
}

Retrieve only parent terms

Retrieve only parent terms from the terms query.

add_action('pre_get_terms', 'get_only_parent_terms');
function get_only_parent_terms($query) {
  $query->query_vars['parent'] = 0;
  return $query;
}

Filter terms by custom field

Filter terms based on a custom field value.

add_action('pre_get_terms', 'filter_terms_by_custom_field');
function filter_terms_by_custom_field($query) {
  $meta_query = array(
    array(
      'key' => 'your_custom_field_key',
      'value' => 'your_custom_field_value',
      'compare' => '='
    )
  );
  $query->query_vars['meta_query'] = $meta_query;
  return $query;
}