Home > Back-end >  Adding together results of numbers from a WP_Query
Adding together results of numbers from a WP_Query

Time:11-23

I've got a custom post type in Wordpress, each post within it has a custom Number field (through Advanced Custom Posts).

When the page loads, I'm performing a query to find all the records that match these args:


$args = array( 
            'post_type' => 'hunters',
            'posts_per_page' => -1, 
            'orderby' => 'title', 
            'order' => 'ASC' ,
            'meta_key'=> 'full_ name',
            'meta_value'=> $email,
            'meta_key'=> 'w3w_location_hit',
            'meta_value'=> $w3w
        );
        $loop = new WP_Query( $args );

I'd like to get the value of code_checks from each record returned in the query and add them all together as a total number - i.e. "there were N code checks made in total" on the page. Is there a way to get each separate value into an array and them add them together, please?

Thank you.

CodePudding user response:

You don't even need to put them into an array - Something like this should work:

// set code checks back to 0
$code_checks = 0;

$args = array( 
    'post_type' => 'hunters',
    'posts_per_page' => -1, 
    'orderby' => 'title', 
    'order' => 'ASC' ,
    'meta_key'=> 'full_ name',
    'meta_value'=> $email,
    'meta_key'=> 'w3w_location_hit',
    'meta_value'=> $w3w
);

$loop = new WP_Query( $args );
    
    while ( $loop->have_posts() ) {
        
        // get code checks in this iteration
        $number = get_field('code_checks');
        
        // add this iteration to total
        $code_checks = $code_checks   $number;
        
    }
    
    // echo total
    echo 'There were ' . $code_checks . ' checks made in total';

/* Restore original Post Data */
wp_reset_postdata();
  • Related