0

So basically i got this custom field value which is stored in $postrating - and under the database field customfield1. I want to grab the value of that field for all posts that have the tag currently being browsed. Then i want to calculate the average value of those numbers and display on the archive.php page when browing a tag.

  • I am not sure form your description - do you use WP native custom fields or do you have (posts?) table extended with extra column or something? – Rarst Apr 5 '11 at 19:30
  • In the database under wp_postmeta the field says meta_id=41 | post_id=19 | meta_key=Rating | meta_value=1 – user4465 Apr 5 '11 at 23:25
1

If its a regular custom field you can add this to your archive.php:

//before the loop
$rating_count = 0;
$total_rating = 0;

//in the loop 
$total_rating = $total_rating + get_post_meta($post->ID,'your_custom_field_name',true);
$rating_count = $rating_count + 1;

//after the loop:
$average = $total_rating / $rating_count;
echo 'the average rating for this tag is: ' . $average;

Update

Now that you've mentioned that there is pagination evolved and you are not getting all of the posts (for example 10/14), you can create a new WP_Query object and use it to get all of the posts (14/14) and check the average. add this code before your loop:

global $wp_query;
$real_query = $wp_query->query; //save reall query
//create new query for all posts of the tag/category/whatever
$args = array_merge( $wp_query->query, array( 'posts_per_page' => '-1' ) );
$average_q = new WP_Query($args);
$rating_count = 0;
$total_rating = 0;
while ($average_q->have_posts()){
    $average_q->the_post();
    $total_rating = $total_rating + get_post_meta($post->ID,'your_custom_field_name',true);
    $rating_count = $rating_count + 1;
}
wp_reset_query();
$average = $total_rating / $rating_count;
echo 'the average rating for this tag is: ' . $average;
query_posts($real_query);
  • i guess i cant use that aproach since all the posts are not present on the page like its only displaying 1-10 of 14 posts on the archive. – user4465 Apr 5 '11 at 23:29
  • @Alex: i updated the answer – Bainternet Apr 5 '11 at 23:50
  • Glad i could help. – Bainternet Apr 6 '11 at 1:57

Your Answer

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