Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
243 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...