0

I will try to explain my question as best for the community as I can.

I have a custom post type in WordPress named "people" (which is the slug).

Each post type belonging to "people" has an Advanced Custom Field associated with it, simply named "number". The field type is a number.

Here is what I want to achieve:

I want to get the values for number for all the posts, on a foreach for example, that carries on for as many posts there are.

I then want to add all of these values up to produce a total.

I know how to handle the calculations in PHP, that's not an issue.

Can you please advice on the best way to collect all the numbers in the custom fields for all posts, and how to store them in order to calculate the total.

Thank you.

1
  • Could you use the CPTs archive? Run a while loop through all the posts and calculate the total inside the loop like $total += $value; (inside). Commented Jul 16, 2018 at 18:52

2 Answers 2

1

You can use the get_posts() (wordpress builtin method) to get all posts from that post type like this:

$args = array( 'post_type'        => 'people',
               'posts_per_page'   => -1
             );

$posts = get_posts($args);

Then you can do a foreach loop through all of the posts like this:

if(!empty($posts))
{
    $total = 0;

    foreach($posts as $p)
    {
       $total += get_field('number', $p->ID);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

One way that I can think of is to get all posts for people post type and then get the field data.

The approach for that will be some thing like:

$peoplePosts = get_posts(
                   array(
                       'post_type'      =>  'people',
                       'posts_per_page'  =>  -1
                   ));
$sum = 0;
print_r(peoplePosts);
if (is_array($peoplePosts)) {
    foreach ( $peoplePosts as $peoplePost) {
        $currentVal = get_field('number', $peoplePost->ID);
        $sum = (float) $sum + (float) $currentVal;
    }
}
echo $sum;

2 Comments

Thank you, this worked! I will point out that there are 2 errors in your example, which broke my page. 1) A missing closing ' after posts_per_page. 2) You didn't close (is_array with a ). After fixing those however, your code worked perfectly, and you have provided a perfect solution to my problem. Thank you!
@T.Sheen My apologies for the error in the code. To be honest I am half asleep right now but I am glad it worked for you. Cheers mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.