Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Last active October 19, 2018 13:33
Show Gist options
  • Save aliboy08/d90350bd188bffc02ccacec119f6e6be to your computer and use it in GitHub Desktop.
Save aliboy08/d90350bd188bffc02ccacec119f6e6be to your computer and use it in GitHub Desktop.
WP Get terms by post type
function ff_get_terms_by_post_type( $taxonomies, $args=array() ){
$args = wp_parse_args($args);
if( !empty($args['post_types']) ){
$args['post_types'] = (array) $args['post_types'];
add_filter( 'terms_clauses', 'ff_get_terms_by_post_type_filter',10,3);
}
return get_terms($taxonomies, $args);
}
function ff_get_terms_by_post_type_filter($pieces, $tax, $args) {
global $wpdb;
$pieces['fields'] .=", COUNT(*) " ;
// Join extra tables to restrict by post type
$pieces['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 ";
// Restrict by post type and group by term_id
$post_types_str = implode(',',$args['post_types']);
$pieces['where'].= $wpdb->prepare(" AND p.post_type IN(%s) GROUP BY t.term_id", $post_types_str);
remove_filter( current_filter(), __FUNCTION__ );
return $pieces;
}
@aliboy08
Copy link
Author

usage:
$regions = ff_get_terms_by_post_type('region', array(
'orderby' => 'name',
'post_types' =>array('post_type_1', 'post_type_2'),
));

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