Skip to content

Instantly share code, notes, and snippets.

@yoren
Created October 25, 2016 09:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yoren/51a436e28397b274ec0b356a388f8b84 to your computer and use it in GitHub Desktop.
Save yoren/51a436e28397b274ec0b356a388f8b84 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);
@JetLewis
Copy link

Cause an error on line 17:
Changing
if ( $args['post_types'] ) {
by
if ( isset($args['post_types']) ) {
does the trick,

Thanks anyway!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment