skip to Main Content

I’m trying to get the total count of a value of a custom field for WooCommerce products. My products are stock of shoes, so for each product I create a custom field for the total pairs quantity. Now I need to display in a new page the total count of pairs.

I tried with this code but the result is always 0

<?php 
$pair_total = 0; //my main variable
$posts = get_posts(array(
'posts_per_page'  => -1,      //get all post
'post_type'     => 'product' //my custom post type
));

if( $posts ) {     
        
    foreach( $posts as $post ){ 
    
      setup_postdata( $post );
      if (get_field('n_totale')) {
        echo get_field('n_totale'); //show individual field(not needed)
        $pair_total = get_field('n_totale') + $pair_total;    //sum all fields 
      }
    }      
  
   wp_reset_postdata(); 

 }?>

  <?php echo '<h1>'.$pair_total.'</h1>'//showing the total value;
  ?>

What can I try next?

2

Answers


  1. Chosen as BEST ANSWER

    I solved with this code:

    $pair_total_1 = 0; //my main variable
    
    $posts = get_posts(array(
    'numberposts' => -1,      //get all post, previously was post_per_page
    'post_type'      => 'product', //my custom post type
    'post_status' => 'publish',
    'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock',
            'compare' => '=',
        )
    )   //I add a query to count only in stock product 
     ));
    if( $posts ) {  
    global $post;
    foreach( $posts as $post ){ 
        setup_postdata( $post);
        if ( get_field( 'n_totale', get_the_ID() ) ) {
            $pair_total_1 = $pair_total_1 + (int) get_field('n_totale', get_the_ID() );    
     //sum all fields 
        }
    }      
    wp_reset_postdata(); 
    }
    
     echo '<p>Totale paia disponibili: '.$pair_total_1.'</p>';}//showing the total value
    

    Thanks to all


  2. check get_field() Try below code.

    <?php 
    
    $pair_total = 0; //my main variable
    
    $posts = get_posts(array(
        'posts_per_page' => -1,      //get all post
        'post_type'      => 'product' //my custom post type
    ));
    
    if( $posts ) {     
        foreach( $posts as $post ){ 
            setup_postdata( $post );
            if ( get_field( 'n_totale', get_the_ID() ) ) {
                $pair_total = $pair_total + (int) get_field('n_totale', get_the_ID() );    //sum all fields 
            }
        }      
        wp_reset_postdata(); 
    }   
    
    echo '<h1>'.$pair_total.'</h1>'//showing the total value;
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search