List categories by author ~ WITH COUNTER ~ (Wordpress)

前端 未结 3 804
野的像风
野的像风 2021-01-15 03:12

This is the code that I\'ve got. It gives a list of the categories a given author has published in. However, I would very much like to have a number next to the category nam

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 03:39

    In SQL exists the count() function, which can count a number of rows. In your case, we want the number of posts, so we could use COUNT(posts.id), like so :

    get_results("
        SELECT DISTINCT(terms.term_id) as ID, terms.name, terms.slug, tax.description, count(posts.id) AS `count`
        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 posts.post_status = 'publish' AND
            posts.post_author = '$author' AND
            tax.taxonomy = 'category'
        ORDER BY terms.name ASC
    ");
    ?>
    
    

    You'll note that I used and alias to rename the count column (otherwise, its name would have been count(posts.id) - not really practical). I have also removed the 1=1 in the WHERE because it is not useful here.

提交回复
热议问题