我在分类法归档模板中面临这种情况(例如。taxonomy-taxname.php
) 对于具有自定义帖子类型和关联类别/标记分类的网站。我想在标题中显示使用分类法的项目数。
在我的分类法归档模板中,我需要找到分类法所表示的术语,然后将其传递给一个函数,以获取使用该术语的自定义post类型项目的数量,这是从标记分类法获得的
// the term we need for this taxonomy
$term_obj = get_queried_object();
// get the term object
$term = get_term( $term_obj->term_id, \'taxname\' );
// get a count of content with this term
$tax_count = get_tax_count(\'taxname\', $term->slug, \'custom-post-type-name\');
// grammar counts
$plural = ( $tax_count == 1) ? \'\' : \'s\';
echo $tax_count . \' Item\' . $plural . \' Tagged "\' . $term->name . \'"\';
用于计数的函数使用WP\\U查询和tax\\U查询:
function tax_count ( $taxonomy, $term, $post_type ) {
// find the number of items in custom post type that use the term in a taxonomy
$args = array(
\'post_type\' => $post_type,
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
\'taxonomy\' => $taxonomy,
\'field\' => \'slug\',
\'terms\' => $term,
),
),
);
$tax_query = new WP_Query( $args );
return ($tax_query->found_posts);
}