• Ok, so I know this question is relatively a simple one, but the answer is alluding me.

    Essentially, a review plugin is saving reviews for listings on a site to the comment meta. I am trying to use FacetWP to automatically filter listing by a few parameters, one being review average. Problem is, as far as I know, wp query doesn’t pull comment meta. So even though there is meta data for the average rating, it won’t search that.

    So I just need to take that comment meta and save it to the post meta for the listings, so I can then call it in FacetWP.

    I was using the code below (and many variations of it…) to try and do this successfully… To no avail. Any help would be appreciated. I’m sure I’m just missing something painfully obvious or just making some simple stupid mistake. Thanks!

    function send_average_rating_to_meta( $post_id ) {
        
    
            if ( empty( $post_id ) ) {
                $post_id = get_the_ID();
            }
    
            $comments = get_comments( array(
                'post_id'  => $post_id,
                'meta_key' => 'pixrating',
                'status'   => 'approve'
            ) );
    
            if ( empty( $comments ) ) {
                return false;
            }
    
            $total = 0;
            foreach ( $comments as $comment ) {
                $current_rating  = get_comment_meta( $comment->comment_ID, 'pixrating', true );
                $total = $total + (double) $current_rating;
            }
    
            $average = $total / count( $comments );
    
            update_post_meta( $post_id, 'pixrating_post', $average );
        }
    
    add_action( 'updated_post_meta', 'send_average_rating_to_meta' );
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    I don’t think ‘updated_post_meta’ is the right action. Wouldn’t it be ‘updated_comment_meta’? When a new review is posted as a comment and the rating is saved to comment meta, a new average can be calculated and saved in post meta.

    You say there is an existing average in comment meta, and you need to copy it to post meta in order to be able to use it in a WP_Query. Then why calculate the average? Why not copy the existing average value?

    It doesn’t make sense to me to keep an average in comment meta, post meta makes more sense. I can’t even imagine how that would work.

    You are correct that WP_Query does not support arguments for comment meta. You could write an SQL query to get the posts you want using comment meta as a condition. Use $wpdb methods to execute your query instead of using WP_Query. This would avoid creating redundant data.

Viewing 1 replies (of 1 total)

The topic ‘Update post meta with comment meta’ is closed to new replies.