Skip to content

Instantly share code, notes, and snippets.

@palicko
Last active December 17, 2016 17:28
Show Gist options
  • Save palicko/d8842600fa9cc058e3a6cbdc23f456b9 to your computer and use it in GitHub Desktop.
Save palicko/d8842600fa9cc058e3a6cbdc23f456b9 to your computer and use it in GitHub Desktop.
Allow to get terms by CPT. Filter terms clauses, so we can get proper terms and posts count related to post type. Usage: add post_type parameter into get_terms() or wp_list_categories() args.
/**
* Extend get terms with post type parameter.
*
* @global $wpdb
* @param string $clauses
* @param string $taxonomy
* @param array $args
* @return string
*/
function custom_terms_clauses( $clauses, $taxonomy, $args ) {
if ( ! empty( $args['post_type'] ) && /*in_array( 'country', $taxonomy ) &&*/ ! is_admin() ) {
global $wpdb;
$post_type = $args['post_type'];
// allow for arrays
if ( is_array( $args['post_type'] ) ) {
$post_type = implode( "','", $args['post_type'] );
}
$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_type ). "') GROUP BY t.term_id";
}
return $clauses;
}
add_filter( 'terms_clauses', 'custom_terms_clauses', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment