Using WordPress ‘parse_term_query’ PHP action

The parse_term_query WordPress PHP action fires after term query variables have been parsed, allowing you to modify the term query before it is executed.

Usage

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

Parameters

  • $query (WP_Term_Query) – The current instance of WP_Term_Query.

More information

See WordPress Developer Resources: parse_term_query

Examples

Modify the ‘orderby’ parameter

Change the order of terms by their term group.

add_action('parse_term_query', 'change_orderby_term_group');
function change_orderby_term_group($query) {
  $query->query_vars['orderby'] = 'term_group';
}

Exclude terms by term ID

Exclude terms with specific IDs from the query.

add_action('parse_term_query', 'exclude_terms_by_id');
function exclude_terms_by_id($query) {
  $exclude_ids = array(5, 9, 15);
  $query->query_vars['exclude'] = $exclude_ids;
}

Set the number of terms per page

Limit the number of terms displayed per page.

add_action('parse_term_query', 'set_terms_per_page');
function set_terms_per_page($query) {
  $query->query_vars['number'] = 10;
}

Hide empty terms

Hide terms with no associated posts.

add_action('parse_term_query', 'hide_empty_terms');
function hide_empty_terms($query) {
  $query->query_vars['hide_empty'] = true;
}

Show terms from a specific parent term

Display terms that have a specific parent term.

add_action('parse_term_query', 'show_terms_by_parent');
function show_terms_by_parent($query) {
  $query->query_vars['parent'] = 3;
}