Hi I'm learning PHP and Woocommerce at the same time! I'm trying to get all the orders which have status processing and the total count for each and display this on a page.
Thus far I can loop through all the orders and get the name and quantity of each.
but as I don't know which product is going to be in the list, I'm not sure how I would compare the name and then add the quantity.
My current output is like this:
prod1 - v1 x 1
Prod2 - v3 x 1
prod2 - v3 x 1
prod3 - v2 x 11
prod3 - v2 x 1
What I would like is:
prod1 - v1 x 1
Prod2 - v3 x 2
prod3 - v2 x 12
The code currently is:
<?php
/*
Template Name: Print Supplier Order
*/
if (!is_user_logged_in() || !current_user_can('manage_options')) wp_die('This page is private.');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php _e('Processing Orders'); ?></title>
<style>
body { background:white; color:black; width: 95%; margin: 0 auto; }
</style>
</head>
<body>
<header>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1 class="title"><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</header>
<section>
<?php
global $woocommerce;
$args = array( 'post_type' => 'shop_order', 'post_status' => 'wc-processing', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
$product_details = array();
$order_items = $order->get_items();
foreach( $order_items as $product ) {
echo $product['name']." x ".$product['qty'];
echo '<br>';
}
?>
<?php endwhile; ?>
</section>
</body>
</html>
Instead of using a
WP_Query
and some heavy code to get your calculations, you should better use this much more lighter and effective version code, usingWPDB
Class (a SQL query):The product count will be based only on the processing oder status and not on product total sales.
Tested and work.
Get the product variations instead (as asked in your comment)
As asked in your comment to get the product variations that are in the order, you will replace the line:
by the following line:
Get all products and variations (Excluding Variable Products)
To get all products including Product Variations but excluding Variable Products use:
Tested and work.
To get them all (even product variations and variable products):
Tested and work.
Method 1
There are a few different ways you could tackle this, but if we want to adjust your code only slightly, then we can achieve this by adding your products in the product loop to a custom array, using the product name as a key, and then working through that array.
Here's an example:
Method 2
Loop through all products, instead of all your orders (after a while, assuming the store is successful, there will probably be a lot more orders than products, so this method might be faster in the long run). Each product stores it's total sales as a meta value, so accessing it is quite simple: