[wp-trac] [WordPress Trac] #18106: get_terms of posts in a specific post_type
WordPress Trac
wp-trac at lists.automattic.com
Wed Jul 4 18:39:45 UTC 2012
#18106: get_terms of posts in a specific post_type
-----------------------------+------------------------------
Reporter: braydonf | Owner:
Type: feature request | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Taxonomy | Version:
Severity: normal | Resolution:
Keywords: |
-----------------------------+------------------------------
Changes (by stephenh1988):
* cc: contact@… (added)
Comment:
Someone asked how to do this on WordPress Stack Exchange
http://wordpress.stackexchange.com/a/57449/9364. After implementing the
above solution (with validation, cache etc). I realised a better way
*might* be to use a wrapper around `get_terms` and make use of the filter.
This wrapper function takes the same arguments as `get_terms`, plus a
`'post_types'` key in the `$args` array. This takes a string|array of post
types. It works for the defaults - but I haven't verified it for all
arguments...
Not exactly future proof (neither solutions are) - but would be great to
see this feature added at some point. I should image that `count` will
cause problems as this is stored in the db. The workaround below replaces
it with an SQL `COUNT(*)`.
{{{
function wpse57444_get_terms($taxonomies, $args=array() ){
if( !empty($args['post_types']) ){
$args['post_types'] = (array) $args['post_types'];
add_filter( 'terms_clauses','wpse_filter_terms_by_cpt',10,3);
function wpse_filter_terms_by_cpt( $pieces, $tax, $args){
global $wpdb;
//Don't use db count
$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 for COUNTing.
$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);
return $pieces;
}
}
$terms = get_terms($taxonomies, $args);
remove_filter( 'terms_clauses','wpse_filter_terms_by_cpt',10);
return $terms;
}
}}}
--
Ticket URL: <http://core.trac.wordpress.org/ticket/18106#comment:4>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software
More information about the wp-trac
mailing list