Skip to content

Instantly share code, notes, and snippets.

@chrisvanpatten
Last active April 2, 2019 14:00
Show Gist options
  • Select an option

  • Save chrisvanpatten/3a5576be67a36e73bd112a252c2b1999 to your computer and use it in GitHub Desktop.

Select an option

Save chrisvanpatten/3a5576be67a36e73bd112a252c2b1999 to your computer and use it in GitHub Desktop.
<?php
add_filter( 'terms_clauses', 'cvp_query_term_alias', 10, 3 );
/**
* Allow querying the term alias field.
*
* @param array $query_clauses
* @param array $taxonomies
* @param array $args
*
* @return array
*/
function cvp_query_term_alias( array $query_clauses, array $taxonomies, array $args ) {
// Make sure we have the field.
if ( ! isset( $args['alias_of'] ) ) {
return $query_clauses;
}
// Massage the alias_of field into an array.
$alias_of = is_numeric( $args['alias_of'] )
? [ (int) $args['alias_of'] ]
: array_map( 'absint', $args['alias_of'] );
// If for some reason the alias field is empty, return early.
if ( empty( $alias_of ) ) {
return $query_clauses;
}
// We are going to build an array of the term groups.
$groups = [];
foreach ( $alias_of as $term_id ) {
$term = get_term( $term_id );
/**
* This is, admittedly, a hack.
*
* The idea here is that if someone wants aliases of a term,
* but the term does not have aliases, the query should
* actually return no results.
*
* So here, we set the group value to PHP_INT_MAX to ensure
* we don't return any results for this particular group.
*
* If you have passed multiple `alias_of` values, you will
* still correctly get results for any terms which _do_ have
* aliases.
*
* But if none of your terms have aliases, you'll get nothing
* back as it's unlikely that we will ever have a term_group
* with an ID equivalent to PHP_INT_MAX.
*
* Again, it's a hack. Shrug!
*/
if ( (int) $term->term_group === 0 ) {
$groups[] = PHP_INT_MAX;
continue;
}
// Add the term groups to our query
$groups[] = $term->term_group;
}
// Get a string version of the groups.
$groups = implode( ", ", array_unique( $groups ) );
// Build the query.
$query_clauses['where'] .= " AND t.term_group IN ({$groups})";
return $query_clauses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment