I have created a shortcode that will returns all products in a loop. I am looking for a way to get the total sales for each product. Right now i'm still having hard time finding the solution.
This is my code:
function loop_ffh_function()
{
?>
<div class="row">
<?php
$args = array(
'numberposts' => -1,
'post_type' => 'product',
'orderby' => 'date');
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
global $product; ?>
<?php
$productID = get_the_ID();
?>
<div class="column">
<a href="<?php echo get_permalink($loop->post->ID) ?>">
<?php the_post_thumbnail('full'); ?>
</a>
<?php
$target = get_field( 'campaign_target_amount' );
?>
<div class="progress" style="margin-top:20px;">
<div class="progress-bar progress-bar-warning progress-bar-striped active" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">
40%
</div>
</div>
<div class="row">
<div class="col-md-8" style="padding-top:7px;">
Target : <b style="font-size: 18px;">RM <?php echo $target;?></b>
</div>
<div class="col-md-4">
<a class="btn" href="<?php echo get_permalink($loop->post->ID) ?>">Donate Now</a>
</div>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
<?php
}
add_shortcode('loop_ffh', 'loop_ffh_function');
How to get a sum amount of sales for each product and display it in the loop?
My Answer:
global $product;
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
$product = wc_get_product(get_the_ID());
$total_sales = $product->get_total_sales();
echo 'Total Sales: ' . $total_sales;
endwhile;
wp_reset_postdata();
}
add_shortcode('loop_ffh', 'loop_ffh_function');
Rate this post
5 of 5 based on 2153 votesComments