Skip to content

Instantly share code, notes, and snippets.

@yoren yoren/functions.php
Created Oct 25, 2016

Embed
What would you like to do?
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);
@yoren

This comment has been minimized.

Copy link
Owner Author

yoren commented Oct 25, 2016

With the hook, you can now use "post_types" as an argument in get_terms function (in WordPress).

@JetLewis

This comment has been minimized.

Copy link

JetLewis commented Aug 20, 2018

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
You can’t perform that action at this time.