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.


Viewing 1 post (of 1 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.