I am using wordpress and ACF for a custom field that has a number in it on each post.
I am trying to query a set of posts and then get the sum of the custom field of the posts queried.
$total_income = 0;
$args = array(
'post_type' => 'acct_income',
'year' => '2023',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$acct_amount = the_field('acct_income_amount');
$total_income = $acct_amount;
echo $total_income;
endwhile;
endif;
This just displays the custom field number in each post and doesn't add them together.
CodePudding user response:
You can use the get_field() function instead of the_field() to retrieve the custom field value and then add it to the $total_income variable. The the_field() function is used to display the field value, whereas the get_field() function is used to retrieve the value. Here is the updated code:
$total_income = 0;
$args = array(
'post_type' => 'acct_income',
'year' => '2023',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$acct_amount = get_field('acct_income_amount');
$total_income = $acct_amount;
endwhile;
echo $total_income;
endif;