Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
    
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 Answer 1

up vote 1 down vote accepted

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);
share|improve this answer
    
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
    
Thanks!! Works great :) –  user4465 Apr 6 '11 at 0:21
    
Glad i could help. –  Bainternet Apr 6 '11 at 1:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.