恐怕这在本地是不可能的查看此跟踪:http://core.trac.wordpress.org/ticket/18106
类似地,在taxonomy admin页面上,帖子数量反映了所有帖子类型。(我很确定也有一张trac罚单)http://core.trac.wordpress.org/ticket/14084
另请参见,this related post.
写了下面的一个解决方案后,我发布了一个更好的方法(尽管在某种意义上你可以做得更多),就是使用get_terms()
呼叫您可以创建一个使用get_terms
并且(有条件地)添加一个过滤器来操作SQL查询(按post类型进行限制)。
该函数的参数与get_terms($taxonomies, $args)
. $args
采用的附加参数post_types
它接受post类型的数组|字符串。
但我不能保证一切都“按预期”进行(我在考虑增加计数)。它似乎只使用默认的$args
对于get_terms
.
function wpse57444_get_terms( $taxonomies, $args=array() ){
//Parse $args in case its a query string.
$args = wp_parse_args($args);
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);
remove_filter( current_filter(), __FUNCTION__ );
return $pieces;
}
} // endif post_types set
return get_terms($taxonomies, $args);
}
使用
$args =array(
\'hide_empty\' => 0,
\'post_types\' =>array(\'country\',\'city\'),
);
$terms = wpse57444_get_terms(\'flag\',$args);
原创作品,灵感来自上述trac票证,(经过测试,对我很有用)
function wpse57444_filter_terms_by_cpt($taxonomy, $post_types=array() ){
global $wpdb;
$post_types=(array) $post_types;
$key = \'wpse_terms\'.md5($taxonomy.serialize($post_types));
$results = wp_cache_get($key);
if ( false === $results ) {
$where =" WHERE 1=1";
if( !empty($post_types) ){
$post_types_str = implode(\',\',$post_types);
$where.= $wpdb->prepare(" AND p.post_type IN(%s)", $post_types_str);
}
$where .= $wpdb->prepare(" AND tt.taxonomy = %s",$taxonomy);
$query = "
SELECT t.*, COUNT(*)
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
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
$where
GROUP BY t.term_id";
$results = $wpdb->get_results( $query );
wp_cache_set( $key, $results );
}
return $results;
}
使用
$terms = wpse57444_filter_terms_by_cpt(\'flag\',array(\'country\',\'city\'));
或
$terms = wpse57444_filter_terms_by_cpt(\'flag\',\'country\');