Support

Account

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

Solving

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.

    Thanks!

  • 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 https://developer.wordpress.org/reference/functions/get_posts/ for details.

  • Hi Laurent,

    I just saw your post about calculating the sum of a number field for a CPT and was wondering if you got it to work and if you could please share the code with me. I am not a programmer and am having a hard time figuring it out.

    My custom post type is ‘investment_project’
    Number field is ‘dashboard_value’

    I need to show the sum of ‘dashboard_value’ through a shortcode in my home page.

    Therefore, my code should look like this?:

    function get_total_investment_value($query_args) {
    $total = 0;
    $posts = get_posts($query_args=’-1′);
    foreach ($posts as $post) {
    $total += get_field(‘dashboard_value’, $post->ID);
    }
    return $total;
    }

    function show_total_investment_value() {
    print get_total_investment_value(array(‘post_type’=>’investment_project’));
    }
    add_shortcode(‘show_the_total_investment_value’, ‘show_total_investment_value’);

    And do I just add this directly as is in the functions.php of my child theme?

    Any help at all will be greatly appreciated!

    Thank you

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

The topic ‘Calculating a sum of a number field for all posts’ is closed to new replies.