Home › Forums › Front-end Issues › How can i sum all values with php from one field?
Hi,
I need to sum values from one field from all posts.
I have a post type with ‘car’ name.
In my query i can display any field, but i need to sum all values from one field like price field.
But, i can’t do that.
My code :
<?php
$income_query = new WP_Query(
array(
'post_type' => 'car',
'post_status' => 'publish',
'posts_per_page' => '-1',
'orderby' => 'date',
'date_query' => array(
'after' => 'today',
'before' => 'tomorrow - 1 second',
'inclusive' => true,
),
// Set new values for relevant arguments.
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1
)
); ?>
<?php
if ($income_query->have_posts()): ?>
<?php
$c = 0;
while ($income_query->have_posts()):
$income_query->the_post();
$field = get_field_object('recog-price');
echo $c += (float)$field['value'];
?>
Anyone can help me ?!
@sirvav 1 option would be to create an array of the values from the query, and then utilize array_sum() PHP function
Reference: https://www.php.net/manual/en/function.array-sum.php
I don’t actually see any reason that your code is not working. When you say “can’t” what is not happening that you expect to happen? What part is not working? Is your query returning the correct posts? Is the loop not working?
Hi John,
This peace of code not working :
echo $c += (float)$field['value'];
The loop work perfectly but, in the last line i can’t get values and sum from all posts.
My filed is textbox and operator entered manually price .
I need get all values field from posts to sum for day and all time income.
This code is return array :
$field = get_field_object('recog-price');
I tried many times, but doesn’t work 🙁
try using get field to just get the value, instead of get_field_object
$value = get_field('recog-price');
$c += (float)$value;
echo $c;
dosen’t work john 🙁
see this image
Your code return list of values …
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.