Home › Forums › General Issues › Total sum of custom field in post
I want to give a post type a certain number value with 2 decimal points.
+——————–+
| 22.00 |
+——————–+
So I created a field, gave it a name of c_percentage and added it to my custom post type. Now what I would like to do is get the sum of all this numbers from each post.
How do I do this? I’ve tried adding getting it through the loop but can’t seem to get it right.
I tried this suggestion here, but seem to have garbled the code.
http://wordpress.stackexchange.com/questions/116522/operations-with-custom-fields-values-in-a-loop/116539
Hi @mvmonroe
Lets first talk about the logic needed.
1. Create a variable to hold the $total. This var starts as 0
2. Loop through all the posts. This code can be found on the docs page under ‘querying posts’ or on google / WP with the get_posts function
3. for each post, find the custom field value via get_field function (read more on the ACF docs page) and add it to the $total var
4. After the loop has ended, your $total var will now contain the correct number
Thanks
E
Thanks, I really shouldn’t try to code after getting back grom the pub. I’ll try this and reply back to the community with my code.
Hi,
I’m doing this. I followed the steps from Elliot and works.
This is my code:
<?php
$total_beficio = 0; //my main variable
$posts = get_posts(array(
'posts_per_page' => -1, //get all post
'post_type' => 'apuestas' //my custom post type
));
if( $posts ) {
foreach( $posts as $post ){
setup_postdata( $post );
if (get_field('beneficio')) {
echo get_field('beneficio'); //show individual field(not needed)
$total_beficio = get_field('beneficio') + $total_beficio; //sum all fields
}
}
wp_reset_postdata();
}?>
<?php echo '<h1>'.$total_beficio.'</h1>'//showing the total value;?>
Well, I need a special function.
I have a numbers fields what are summing.
And I have a date field too. (Single date for every post, not start/end date)
I need divide the field in months and years.
Example:
2017
January
30
February
23
….
2016
January
23
February
73
How I can achieve this?
EDIT: I don’t need the wp published date. I need use my acf date field.
Regards
The topic ‘Total sum of custom field in post’ is closed to new replies.
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.