Support » Fixing WordPress » Foreach statement… I think?

  • Alright – when a user leaves a comment on a post they can leave an overall rating. I store this rating in a variable, lets call it $overall.

    So basically I need to get each comment’s $overall value, for every single comment for that particular post.

    Would I use a foreach statement? Like, foreach $post_id get $overall foreach comment…

    I’m looking for some guidance on the best way to approach this.

Viewing 5 replies - 1 through 5 (of 5 total)
  • You can do it that way, but it’s not the most efficient. It will work fine and most users won’t notice any difference though.

    If you’re any good with SQL I’d recommend that you write your own query to pull in the values. That way it’s a single query executed once and output rather then a loop and possibly a whole bunch of queries running each time. As a complete guess/example…

      SUM(meta_value) AS overall
    FROM wp_commentmeta
    WHERE comment_id = '".$comment_id."'
      AND meta_key = 'overall'

    I’ve made a few assumptions there, like the attribute name, but that’s the general idea of how it’d work.

    It’d be AVG(meta_value) yea?

    Yes, thats right Andrew. That’s what I get for using SUM() to much. 🙂

    hmmm… I see where you are going with this… OK, so if I have two meta values, and want to add them first THEN divide by comment count… how do you actually get that value out of the query?

    Here’s my chicken scratch thought process on it..

    picture here

    You don’t need to. As Andrew said before you should use


    That takes care of all of that for you.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Foreach statement… I think?’ is closed to new replies.