Search code examples
phpwordpressadvanced-custom-fieldsacfpro

HOW TO COUNT() value in the same field from custom post type ACF WORDPRESS


I have field name "amount" from my custom post type all I want is every time I post with the amount field I created through ACF will count() the field amount

ex.

loop
  // The task is a post in custom post type different amount 
  // the first value post ex. 10, Second post 20, Third post will be 30

  // I am trying this but not work
  $varAmount = get_field('amount');
  $varCount = count($varAmount);




 echo $varCount;

  Output expected is: 60

  // but showing 1010101;
  // how to do that 60 instead of 101010?


/loop
$faq = new  WP_Query($args_faqs);

if ( $faq->have_posts() ) {
/*
 * Begin the loop tags post
 */

    #echo count(get_field('loan_amount_applied'));
     $total_amount = 0; 
     $amountapplied = get_field('loan_amount_applied'); 
     $total_amount += $amountapplied; 

     $varCount = count($total_amount); 

     // array() = $amountapplied);
     // if(is_array($amountappliedCOntainer)) {
     // $total_amount = count($amountappliedCOntainer);

while ( $faq->have_posts() ) {
         $faq->the_post();

enter image description here


Solution

  • Welcome to SO. Since you need to count the values of multiple posts, you need to initialize a variable with value as 0 outside your loop. and then you need to add the value of amount(ACF FIELD) to that variable and then echo it.

    Use the below code.

    <?php if ( have_posts() ) : 
    
    $counter = 0;
    
    /* Start the Loop */
    while ( have_posts() ) :
    the_post();
    $varAmount = get_field('amount');
    $counter += $varAmount;
    echo $counter;
    endwhile;
    
    endif;
    ?>