List categories by author ~ WITH COUNTER ~ (Wordpress)

前端 未结 3 829
野的像风
野的像风 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:28

    I figured it out... had to run to separate SELECT functions: one to fetch the list of categories, and then one more functions within that loop to count how many entries there is within the category. I would have preferred to have these two loops as one, but this works out for me.

    get_results("
    
    SELECT DISTINCT(terms.term_id) as ID, terms.name, terms.slug, tax.description
    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
    ");
    
    
    // This loop picks up categories
    foreach($categories as $category) : 
    
    $catid = $category->ID;
    
    // Now, inside the loop, we need to count how many posts that the Author has published.
    $counter = "SELECT COUNT(*)
    FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    WHERE $wpdb->term_taxonomy.term_id = $catid
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->posts.post_status = 'publish'
    AND post_author = '$author'
    ";
    
    $user_count = $wpdb->get_var($counter);
    
    echo '
    ' . $category->name . '
    ' . $user_count . ' posts
    '; endforeach; ?>

提交回复
热议问题