这可以很容易地用$wpdb
, 以下是我的方法:
function GetTop2CategoryByUser($user_id, $taxonomy){
global $wpdb;
$results=$wpdb->get_results( $wpdb->prepare(
"
SELECT tt.term_id as category, COUNT(p.ID) as count
FROM $wpdb->posts p
JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
JOIN $wpdb->term_taxonomy tt
ON tt.term_taxonomy_id = tr.term_taxonomy_id
AND (tt.taxonomy = %s AND tt.term_taxonomy_id != 1)
WHERE p.post_author = %s
GROUP BY tt.term_id
ORDER BY count DESC LIMIT 2
",
$taxonomy,
$user_id
) );
return $results;
}
// Get user\'s top 2 published categories
$user_top_cat = GetTop2CategoryByUser($user_ID,$taxonomy)
// $results should return
Array
(
[0] => stdClass Object
(
[term_id] => 4
[count] => 8345
)
[1] => stdClass Object
(
[term_id] => 3
[count] => 45345
)
)
检索类别ID而不是名称会稍微快一些。