另一个答案没有问题,但我想我应该将其添加为另一种方法,因为它很简单,并且使用WP来计算SQL查询。由于有额外的查询get_post_meta
作用
$user_id = 1;
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'ASC\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'post_author\',
\'value\' => $user_id
),
array(
\'key\' => \'rating\',
\'compare\' => \'!=\', // or\'>\'
\'value\' => 0
),
array(
\'key\' => \'anonymous\',
\'compare\' => \'!=\',
\'value\' => true
),
array(
\'key\' => \'original_author\',
\'compare\' => \'!=\',
\'value\' => \'\'
)
)
);
$RelevantPosts = get_posts($args);
$ratings = array();
foreach($RelevantPosts as $RelevantPost) {
$ratings[] = get_post_meta($RelevantPost->ID, \'rating\' , true);
}
if ( $RelevantPosts ) {
$average_rating = round(array_sum($ratings) / count($ratings), 1);
} else {
$average_rating = 0;
}
然而,它很容易阅读和理解,只要它不是大规模运行(如一次针对所有帖子),它就可以用于资源。