Skip to content

Instantly share code, notes, and snippets.

@temsool
Forked from yoren/functions.php
Created April 27, 2021 11:41
Show Gist options
  • Save temsool/c59f9e7aab7b2c0e2e8e4913cd322a16 to your computer and use it in GitHub Desktop.
Save temsool/c59f9e7aab7b2c0e2e8e4913cd322a16 to your computer and use it in GitHub Desktop.
Get terms by custom post types and taxonomy
<?php
/**
* my_terms_clauses
*
* filter the terms clauses
*
* @param $clauses array
* @param $taxonomy string
* @param $args array
* @return array
* @link http://wordpress.stackexchange.com/a/183200/45728
**/
function my_terms_clauses( $clauses, $taxonomy, $args ) {
global $wpdb;
if ( $args['post_types'] ) {
$post_types = $args['post_types'];
// allow for arrays
if ( is_array($args['post_types']) ) {
$post_types = implode("','", $args['post_types']);
}
$clauses['join'] .= " INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id";
$clauses['where'] .= " AND p.post_type IN ('". esc_sql( $post_types ). "') GROUP BY t.term_id";
}
return $clauses;
}
add_filter('terms_clauses', 'my_terms_clauses', 99999, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment