Home Forums General Issues Calculating a sum of a number field for all posts


Calculating a sum of a number field for all posts

  • Hi everyone,

    I have a Custom Post Type named “Person”.
    Each posts in that CPT have an ACF number field “age_number”.

    I want to show by a shortcode on the frontend of my website, the sum of the field “age_number” for all the posts in this CPT.

    I found a function that seems to be working at the beginning but after a couple posts added, the results are wrong. Not sure what is going on in the formula.

    Here’s the piece of code I added in my functions.php:

    function get_total_age($query_args) {
        $total = 0;
        $posts = get_posts($query_args);
        foreach ($posts as $post) {
            $total += get_field('age_number', $post->ID);
        return $total;
    function show_total_age() {
        print get_total_age(array('post_type'=>'person'));
    add_shortcode('show_the_total_age', 'show_total_age');

    What I’m I doing wrong? I’m a not an expert in PHP so any help is really appreciated.


  • Hi,

    You don’t explicitly say what’s wrong with the results you’re seeing. But I can think of a few reasons that you don’t see the results you’re expecting. The most obvious one is the call to get_posts.

    In the args array passed to get_posts, you don’t specify ‘numberposts’. If you leave it out, it will default to 5. If you want all posts, you need to specify -1. Please se for details.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.