WordPress.org

Ready to get started?Download WordPress

Forums

Foreach statement... I think? (6 posts)

  1. Sarah_Frantz
    Member
    Posted 1 year ago #

    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.

  2. catacaustic
    Member
    Posted 1 year ago #

    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...

    SELECT
      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.

  3. Andrew Bartel
    Member
    Posted 1 year ago #

    It'd be AVG(meta_value) yea?

  4. catacaustic
    Member
    Posted 1 year ago #

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

  5. Sarah_Frantz
    Member
    Posted 1 year ago #

    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

  6. catacaustic
    Member
    Posted 1 year ago #

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

    AVG(meta_value)

    That takes care of all of that for you.

Topic Closed

This topic has been closed to new replies.

About this Topic