0

我正在使用以下函数/简码来使用 ACF 输出平均全球评级:

function get_average_rating($post_id) {

   $rating_sum = 0;

   $reviews_of_post = get_posts( array(
    'post_type' => 'avis',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => 'produit',
            'value' => $post_id,
            'compare' => '=',
        ),
    ),
) );

if ( empty( $reviews_of_post ) ) {
    return 0;
}

foreach ( $reviews_of_post as $review ) {
    $rating_sum += get_field( 'note_client', 'post_' . $review->ID);
}

return number_format((float)($rating_sum / count( $reviews_of_post )),1, ',', '');
}

add_shortcode( 'note-clients', 'get_average_rating');

它总是返回 0,除非我手动输入帖子 ID,例如:

'meta_query' => array(
    array(
        'key' => 'produit',
        'value' => 1234,
        'compare' => '=',
    ),
),

我怎样才能解决这个问题 ?

非常感谢 !

4

3 回答 3

1

global $post;在你的函数之前声明。

Wordpress 将 $post 用于循环中的许多功能。为避免以后发生任何冲突,您应该考虑使用wp_reset_query

于 2019-12-04T14:37:32.230 回答
0

1. 将键 'key' => 'produit' 更改为 'key' => 'product',

2.

foreach ( $reviews_of_post as $review ) {
    $rating_sum += get_field( 'note_client', 'post_' . $review->ID);
}

**to**

foreach ( $reviews_of_post as $review ) {
 $post_id   = 'post_' . $review->ID ;
 $rating_sum += get_field( 'note_client', $post_id );
 }

确认 ACF 密钥 (note_client) 正确

3. 改变这个

add_shortcode( 'note-clients', 'get_average_rating');

add_shortcode( 'average_rating', 'get_average_rating');
于 2019-12-04T12:14:22.460 回答
-1

请尝试使用您的帖子静态 ID:

$post_id = 9; //add here your static post id
   $reviews_of_post = get_posts( array(
       'post_type' => 'avis',
       'posts_per_page' => -1,
       'meta_query' => array(
           array(
               'key' => 'produit',
               'value' => $post_id,
               'compare' => '=',
           ),
       ),
   ) );
于 2019-12-04T13:23:33.120 回答