在我的作者页面上,我当前有一个由以下代码生成的作者发布的类别列表:
<?php
$categories = $wpdb->get_results("
SELECT DISTINCT(terms.term_id) as ID, terms.name, terms.slug
FROM $wpdb->posts as posts
LEFT JOIN $wpdb->term_relationships as relationships ON posts.ID = relationships.object_ID
LEFT JOIN $wpdb->term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN $wpdb->terms as terms ON tax.term_id = terms.term_id
WHERE 1=1 AND (
posts.post_status = \'publish\' AND
posts.post_author = $curauth->ID AND
tax.taxonomy = \'category\' )
ORDER BY terms.name ASC
");
$x = 0;
?>
<ul class="category-list">
<?php foreach($categories as $category) : ?>
<?php if( $x%2 ){ ?>
<li class="odd">
<?php } else { ?>
<li>
<?php } ?>
<a href="<?php echo get_category_link( $category->ID ); ?>" title="<?php echo $category->name ?>"><?php echo $category->name ?></a>
</li>
<?php $x++; endforeach; ?>
</ul>
我要做的是在foreach循环中的每个类别中,在括号中的类别旁边添加帖子的数量。
你知道我该怎么做吗?
谢谢
SO网友:Bainternet
您可以尝试一种不那么优雅但行之有效的解决方案,即获取所有用户的帖子并统计其类别:
$query = new WP_Query(array(
\'author\' => $curauth->ID,
\'posts_per_page\' => -1
)
);
if ($query->have_posts()){
$u_cats = array();
while ($query->have_posts()){
$query->the_post();
$terms = wp_get_object_terms( $post->ID, \'category\');
foreach ($terms as $term){
if (is_array($u_cats[$term->term_id])){
$u_cats[$term->term_id][\'count\'] = $u_cats[$term->term_id][\'count\'] +1;
}else{
$u_cats[$term->term_id][\'count\'] = 1;
$u_cats[$term->term_id][\'name\'] = $term->name;
$u_cats[$term->term_id][\'ID\'] = $term->term_id ;
}
}
}
//Now $u_cats is an array of categories each with name, ID and author post count for that category
$x = 0;
?>
<ul class="category-list">
<?php foreach($u_cats as $category) :
if( $x%2 ){ ?>
<li class="odd">
<?php } else { ?>
<li>
<?php } ?>
<a href="<?php echo get_category_link( $category[\'ID\'] ); ?>" title="<?php echo $category[\'name\'];?>"><?php echo $category[\'name\']; ?></a>(<?php echo $category[\'count\']; ?>)
</li>
<?php $x++; endforeach; ?>
</ul>
<?php
}