Support

Account

Home Forums Front-end Issues How can i sum all values with php from one field?

Solving

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;
    
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.