功能和帖子ID出现问题

时间:2019-12-04 11:43:08

标签: wordpress foreach relationship advanced-custom-fields meta-query

我正在使用以下功能/简码,以便使用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' => '=',
    ),
),

我该如何解决?

非常感谢!

3 个答案:

答案 0 :(得分:1)

在函数之前声明global $post;

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

答案 1 :(得分:0)

1。将密钥'key'=>'产品'更改为'key'=>'产品',

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');

答案 2 :(得分:-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' => '=',
           ),
       ),
   ) );
相关问题