作者页面-类别列表加上该类别中的帖子数量

时间:2011-06-30 作者:Probocop

在我的作者页面上,我当前有一个由以下代码生成的作者发布的类别列表:

<?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循环中的每个类别中,在括号中的类别旁边添加帖子的数量。

你知道我该怎么做吗?

谢谢

2 个回复
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 

}

SO网友:TheDeadMedic

why not use wp_list_categories?

wp_list_categories( \'show_count=1\' );
结束

相关推荐

Permalinks for quote authors

What I have:引用的网站,格式为:“引用文本”-引用作者参见quotup.com 对于我的考试网站(我为考试中的亵渎行为提前道歉)。What I\'m after:单击“-Quote Author”将启动一个包含该Quote Author所有引用的页面,URL为:示例。史蒂夫·史蒂文森,其中史蒂夫·史蒂文森是引文作者。What I\'ve done:创建了一个名为wp\\u qauthor的自定义表,该表通过post\\u meta(qauthor\\u id)绑定到wp\\u posts向函数