0

I have created a custom post type named “Rating” that I’m using to add customer rating sections to my website. Each rating post has the ability to have a:

  • Title
  • Comment section
  • Featured Photo
  • Tags
  • and I’m using custom fields to add 1-5 ratings for Professional Rating, Efficiency Rating, and Referral Rating.

I can pull in the Rating posts based upon their associated tags no problem and I can also pull in all of the custom field data with no problem.

That being said, I’m also wanting to include the average overall rating for each custom field rating. How would I aggregate or get all of the custom field data for a single tag?

Example:

  • I have a tag named company

  • There are 50 Rating posts that have the company tag associated with them and each post has the 1-5 ratings for Professional Rating, Efficiency Rating, and Referral Rating.

  • How can I get or query the DB such that I can get the average rating for say the Professional Rating custom field type for all of those posts associated with the company tag?

Hopefully this makes sense and I have explained my question clear enough but please let me know if I can further clarify.

0

If you use those custom fields only for the company tagged posts, then it's sufficient to retrieve the custom fields without worrying about posts and tags:

$tags = array('Professional Rating', 'Efficiency Rating', 'Referral Rating');

foreach ($tags as $tag)
{
    $result = $wpdb->get_col( "SELECT meta_value FROM wp_postmeta WHERE meta_key = '$tag'" );

    $avg = empty($result) ? 0 : ( array_sum($result) / count($result) );

    echo "Average for $tag: $avg" . PHP_EOL;
}

This doesn't check if the company posts are published or not. For that use this query:

SELECT meta_value FROM wp_posts p, wp_postmeta pm
WHERE p.ID=pm.post_id AND p.post_status='publish' AND meta_key = '$tag'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.