いくつか投稿タイプを使っていて、カスタムタクソノミーが重複する場合(例えば「カテゴリー」を「投稿」と「固定ページ」で使っている場合)、get_terms()したときのcount対象は、通常だと 投稿 と 固定ページ と合算したものになってしまう。
しかし、投稿だけのカウント、固定ページだけのカウントがほしいときもある。はず。
その方法について調べたところ、こちらの方法が使えそう:
使い方
functions.php に
// Handle the post_type parameter given in get_terms function
function hoge_terms_clauses($clauses, $taxonomy, $args) {
if (!empty($args['post_type'])) {
global $wpdb;
$post_types = array();
if( $args['post_type'] ){
foreach($args['post_type'] as $cpt) {
$post_types[] = "'".$cpt."'";
}
}
if(!empty($post_types)) {
$clauses['fields'] = 'DISTINCT '.str_replace('tt.*', 'tt.term_taxonomy_id, tt.term_id, tt.taxonomy, tt.description, tt.parent', $clauses['fields']).', COUNT(t.term_id) AS count';
$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 ('.implode(',', $post_types).')';
$clauses['orderby'] = 'GROUP BY t.term_id '.$clauses['orderby'];
}
}
// print_r($clauses);exit;
return $clauses;
}
add_filter('terms_clauses', 'hoge_terms_clauses', 10, 3);
これを見てわかるように、get_terms( $args ) の$argsに、でpost_typeをarrayで渡せばよい。
よって、get_terms()するときに、
$product_cats = get_terms( array( 'taxonomy' => 'category',
'post_type' => array('post'),
'hide_empty' => 0, 'orderby' => 'name', 'order'=>'ASC' ) ) ;
のようにすればOK。
