您可以使用此函数,将其添加到主题的functions.php
文件,以更新保存在名为_avg_rating
(但您当然可以重命名它)—私有元的名称以下划线开头(_
):
function update_post_avg_rating( $comment_id, $post_id = 0 ) {
if ( ! $post_id ) {
if ( ! $comment = get_comment( $comment_id ) ) {
return false;
}
$post_id = $comment->comment_post_ID;
}
// Retrieve the ID of all rating comments in post $post_id.
$ids = get_comments( [
\'meta_key\' => \'rating\',
\'post_id\' => $post_id,
\'fields\' => \'ids\',
\'status\' => \'all\',
] );
// Calculate the average rating (using a custom MySQL query).
$avg = 0;
if ( ! empty( $ids ) ) {
global $wpdb;
$avg = $wpdb->get_var( "
SELECT AVG(meta_value + 0) FROM {$wpdb->prefix}commentmeta
WHERE meta_key = \'rating\'
AND comment_id IN (" . implode( \',\', $ids ) . ")
" );
}
// Update the average rating.
update_post_meta( $post_id, \'_avg_rating\', $avg );
}
然后在保存后评价后调用该函数,如下所示:
function save_comment_meta_phone( $comment_id ) {
if ( ! empty( $_POST[\'rating\'] ) ) {
$rating = sanitize_text_field( $_POST[\'rating\'] );
// Save the post rating.
add_comment_meta( $comment_id, \'rating\', $rating );
// Then update the average rating.
update_post_avg_rating( $comment_id );
}
}
顺便说一句,您可能需要重命名
save_comment_meta_phone()
功能到
save_comment_meta_rating
?.. (只是一个建议)
在update_post_avg_rating()
代码,在get_comments()
呼叫,您可以设置status
到approve
如果您只想包括已批准的后期评级。
已删除更新,但您始终可以查看答案的修订
已删除更新#2,但您始终可以查看答案的修订
更新#3
希望这些可以帮助您使用
_avg_rating
元数据:
要显示单个帖子的平均评分,您可以使用get_post_meta()
像这样:
$avg_rating = get_post_meta( get_the_ID(), \'_avg_rating\', true );
$avg_rating = $avg_rating ? number_format_i18n( $avg_rating, 1 ) : 0;
echo $avg_rating;
按_avg_rating
meta,但仍包括不具有_avg_rating
meta,可以使用键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键控键meta_query
像这样:$q = new WP_Query( array(
\'post_type\' => \'post\',
\'meta_query\' => array(
\'relation\' => \'OR\',
\'avg_rating_clause\' => array(
\'key\' => \'_avg_rating\',
\'compare\' => \'EXISTS\',
\'type\' => \'DECIMAL\',
),
\'avg_rating_clause2\' => array(
\'key\' => \'_avg_rating\',
\'compare\' => \'NOT EXISTS\',
\'type\' => \'DECIMAL\',
),
),
\'orderby\' => array(
\'avg_rating_clause2\' => \'DESC\',
\'date\' => \'DESC\',
),
//...
) );
// Sample for displaying the posts.
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
$avg_rating = get_post_meta( get_the_ID(), \'_avg_rating\', true );
$avg_rating = $avg_rating ? number_format_i18n( $avg_rating, 1 ) : 0;
the_title( \'<h2>\', \' (Avg. Rating: \' . $avg_rating . \')</h2>\' );
}
}
请参见here 有关meta_query
.