0

I am trying to add up custom fields from different posts. The array I created is not working.

Here is the code.

<?php $totalpricearray = query_posts('post_type=items&author='.$thisauthorID.'&tag='.$thispostID); while (have_posts()) : the_post(); 

    $productprice = get_post_meta($post->ID, "productprice", true);
    $productquantity = get_post_meta($post->ID, "productquantity", true);
    $totalproductprice = ($productprice * $productquantity);
    echo $totalproductprice, ',';
         endwhile;

         $totalprice = array($totalpricearray);
         echo array_sum($totalprice); ?>

Any ideas,

Marvellous

(ps just noticed array is working but equals 0)

1
<?php
$totalprice_posts = get_posts('post_type=items&author='.$thisauthorID.'&tag='.$thispostID.'&numberposts=-1');
$totalprice_array = array();
foreach ($totalprice_posts as $post) {
    $productprice = get_post_meta($post->ID, "productprice", true);
    $productquantity = get_post_meta($post->ID, "productquantity", true);
    $totalproductprice = ($productprice * $productquantity);
    array_push($totalprice_array, $totalproductprice);
}
echo implode(',', $totalprice_array);
echo array_sum($totalprice_array);
?
  • Brilliant although its not adding up the last value in the array – Robin I Knight Feb 22 '11 at 15:42
  • @Robin I Knight: That sounds a bit unlikely...the last two lines are merely PHP core functions. If there were a difference it would be a bug in PHP, unless there's a type casting problem with the values. – wyrfel Feb 22 '11 at 15:59
  • I checked and found no explanation for it. Yet when I changed get_posts to query_posts it did add the last value. – Robin I Knight Feb 22 '11 at 16:01
  • @Robin I Knight FYI I rejected your edit because query_posts() should never be used for secondary loops. I am not sure why results between two function might differ in your case, but switching to query post will likely cause more issues than it solves. – Rarst Feb 22 '11 at 16:20
  • You know more than me I'm not arguing. Looking at it furhter though, if by secondary loop do you mean a loop within a loop, because it isn't. There are in fact 2 other loops above it one containing the page (post_type=bookings) and the other containing items (post_type=items). Both of these loops have come to their conclusion before the beginning of this one. loop is executed in full above – Robin I Knight Feb 22 '11 at 16:45

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.