Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

php - Sum of all custom fields for category

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...