类别的所有自定义字段的总和 [英] Sum of all custom fields for category
问题描述
我在名为 number
的帖子上有一个自定义字段.
I've got a custom field on posts called number
.
在category.php的前端,我需要总计当前类别中所有具有 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
.
例如,如果当前类别有3个帖子,并且每个帖子中的 number
值分别为 1
, 5
和 10
,然后在前端需要显示总计 16
.
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
.
我不确定从哪里开始.
我目前的循环:
<?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; ?>
感谢您的帮助.
推荐答案
所要实现的简短版本(这也会减少对数据库的调用)将类似于以下内容:
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>
正如另一条评论中所述,您不需要其他循环,因为您的帖子已经存在于 $ wp_query
中.
As mentioned in another comment, you don't need another loop, as your posts already exist in $wp_query
.
这篇关于类别的所有自定义字段的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!