RiotAct
RiotAct

Reputation: 773

Get total product purchased count with specific product attributes in Woocommerce

I am creating a custom report using WooCommerce and it is working, but it is using a ton of resources, and it needs to be much larger and will time out if I increase its size. I am certain there is a better way to do this.

I am running muliple queries to see how many products of specific colors and sizes have been ordered. Currently, these are separate queries and not efficient. Here is my code:

This is the function that gets the quantity ordered:

function get_order_by_product_id($product_id, $product_color, $product_size) {
    $args = array ( 
            'limit' => '-1',
            'status' => 'processing',
    );
    $orders = wc_get_orders( $args );
    if($orders) :
        $total = 0;
        foreach( $orders as $order) :
            $order_id = $order->get_id();
            $single_order = wc_get_order( $order_id ); 

            foreach ($single_order->get_items() as $item_id => $item_data) :
                $product = $item_data->get_product();
                $productID = $single_order->get_item_meta($item_id, '_product_id', true);
                $product_name = $product->get_name();
                $color = $single_order->get_item_meta($item_id, 'pa_colors', true);
                $size = $single_order->get_item_meta($item_id, 'pa_sizes', true);
                $item_quantity = $item_data->get_quantity();

                if($productID == $product_id && $color == $product_color && $size == $product_size ) :
                    $total += $item_quantity;
                endif;

            endforeach;
        endforeach;
        echo $total;
    endif;
} 

This is a call to the function:

get_order_by_product_id(47652, 'black', 'xs');

Currently, in order to make this work, I am calling the function over and over again for each product id, color and size. As I said, it works, but is a resource hog.

Any ideas for increasing efficiency would be greatly appreciated!

Upvotes: 1

Views: 2444

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 254211

This can be done in a simple lighter SQL query with the following function:

/*
 * @param (int)    $product_id 
 * @param (string) $colors     slug term for "pa_colors" product attribute
 * @param (string) $sizes      slug term for "pa_sizes"  product attribute
 * @param (string) $status     Optional: Order status ("processing" by default)
**/
function get_ordered_product_count( $product_id, $colors, $sizes, $status='processing' ){
    return $wpdb->get_var( "
        SELECT SUM(woim.meta_value)
        FROM {$wpdb->prefix}posts as p
        INNER JOIN {$wpdb->prefix}woocommerce_order_items as woi ON p.ID = woi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim ON woi.order_item_id = woim.order_item_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim1 ON woi.order_item_id = woim1.order_item_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim2 ON woi.order_item_id = woim2.order_item_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta as woim3 ON woi.order_item_id = woim3.order_item_id
        WHERE p.post_type LIKE 'shop_order'
        AND p.post_status LIKE 'wc-$status'
        AND woim.meta_key LIKE '_qty'
        AND woim1.meta_key LIKE 'pa_colors'
        AND woim1.meta_value LIKE '$colors'
        AND woim2.meta_key LIKE 'pa_sizes'
        AND woim2.meta_value LIKE '$sizes'
        AND woim3.meta_key LIKE '_product_id'
        AND woim3.meta_value = $product_id
    " );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE examples:

  • For "Processing" Orders status: get_ordered_product_count(47652, 'black', 'xs');
  • For specific Orders status: get_ordered_product_count(47652, 'black', 'xs', 'completed');

Upvotes: 3

Ronald
Ronald

Reputation: 36

To count all (published) products with a specific attribute eq with a color 'blue' or 'black' you can use:

$colors = 'black, blue';  
$args = array( 
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'ignore_sticky_posts'   => 1,
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
                )
            ),
            'tax_query'             => array(
                array(
                    'taxonomy'      => 'pa_color',
                    'terms'         => explode(",",$colors),
                    'field'         => 'slug',
                    'operator'      => 'IN'
                )                   
            )
        );

echo count (wc_get_products($args));

Upvotes: 0

Related Questions