Sum of all custom fields for category

273 views Asked by At

I've got a custom field on posts called number.

On the front-end in category.php, I need to total up the value of all posts in the current category that have number.

So for example, if the current category had 3 posts, and in each post the number values were 1, 5 and 10 respectively, then on the front-end it needs to display the total 16.

I'm not entirely sure where to start with this.

The loop I have at the moment:

<?php if ( have_posts() ) : ?>

        <h1><?php printf( __( 'Category Archives: %s', 'twentythirteen' ), single_cat_title( '', false ) ); ?></h1>
        <p></p>

    <?php /* The loop */ ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'content', get_post_format() ); ?>
    <?php endwhile; ?>

<?php else : ?>
    <?php // ?>
<?php endif; ?>

Any help is appreciated.

3

There are 3 answers

1
User_FTW On

Thanks everyone. There was a lot there that helped me arrive at this solution (and a little help from Google):

<?php 
$args = array(
    'numberposts' => -1,
    'offset' => 0, 
    'category' => $category
);
$numbers = get_posts( $args );

$total = 0;
foreach( $numbers as $numbersID ) {
    $single = get_post_meta( $numbersID->ID, 'numbers', true );
    $total += $single;
}
echo $total;
?>

The key was knowing to increment a variable += as @rnevius suggested, which I didn't know about.

1
Anticom On

Supposing you're using MySQL use SUM() Method to achive your goals. Query might look something like SELECT SUM(number) FROM category WHERE [drill down to a specific set of categories if neccesary];

1
rnevius On

A shorter version of what you're trying to achieve (which also reduces calls to the database) would look something like the following:

<p>
    <?php
        $total = 0;
        foreach( $wp_query->posts as $number ) {
            $total += get_post_meta( $number->ID, 'numbers', true );
        }
        echo $total;
    ?>
</p>

As mentioned in another comment, you don't need another loop, as your posts already exist in $wp_query.