【问题标题】:Sum of all custom fields for category类别的所有自定义字段的总和
【发布时间】:2015-08-26 16:12:25
【问题描述】:

我在帖子上有一个名为 number 的自定义字段。

在category.php的前端,我需要汇总当前类别中所有具有number的帖子的值。

例如,如果当前类别有 3 个帖子,并且每个帖子中 number 的值分别为 1510,那么前端需要显示总数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; ?>

感谢任何帮助。

【问题讨论】:

  • 显示你在category.php得到了什么
  • 获取字段并添加它们时会发生什么?
  • @Viral - 这是默认的 category.php 页面。没什么特别的。
  • @mevius - 这就是我需要做的。获取当前类别的每个帖子上的“数字”字段,并将它们总计以显示在 category.php 上的总数
  • get_field() 在每个帖子的循环中,然后增加一个变量 +=

标签: php wordpress categories


【解决方案1】:

您尝试实现的目标的较短版本(这也减少了对数据库的调用)如下所示:

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

正如另一条评论中提到的,您不需要另一个循环,因为您的帖子已经存在于$wp_query

【讨论】:

  • 是的,这就是我所说的。至少有人读过我的 cmets :-)
【解决方案2】:

谢谢大家。那里有很多东西帮助我找到了这个解决方案(还有来自 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;
?>

关键是知道要按照@rnevius 的建议增加一个变量 +=,我不知道。

【讨论】:

  • 不要运行另一个查询,它很昂贵,使用$wp_query-&gt;posts,您所有的帖子都存储在那里。而不是$numbers = get_posts( $args );,而是$numbers = $wp_query-&gt;posts
【解决方案3】:

假设你正在使用 MySQL 使用 SUM() 方法来实现你的目标。查询可能类似于SELECT SUM(number) FROM category WHERE [drill down to a specific set of categories if neccesary];

【讨论】:

  • 为什么我的回答被否决了?当我发布它时,问题中没有附加代码,所以我不得不做出假设。
猜你喜欢
  • 1970-01-01
  • 2016-04-04
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2015-12-30
相关资源
最近更新 更多