.
WORDPRESS PLUGINS ABOUT

Create WooCommerce PHP Function to get the top 3 products bought at the same time from a product_id

2 minute read, 1 if you're quick

Quite a long post title this one, if you would like a function in WordPress/WooCommerce to list the top 3 other products bought at the same time as a supplied product_id here is the code.

I am using MySQL join commands to connect up the following three tables:
posts
woocommerce_order_items
woocommerce_order_itemmeta

Here is the function to add to your plugin or functions.php file:

function list_top3_products() {

global $wpdb;
$product_id = '1722';

$query = "
	SELECT {$wpdb->prefix}posts.ID, {$wpdb->prefix}posts.post_title, COUNT(oi2.meta_value) as count
	FROM {$wpdb->prefix}posts
	JOIN {$wpdb->prefix}woocommerce_order_items as oi1 ON {$wpdb->prefix}posts.ID = oi1.order_id
	JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oi2 ON oi1.order_item_id = oi2.order_item_id
	WHERE {$wpdb->prefix}posts.post_type = 'shop_order'
	AND {$wpdb->prefix}posts.post_status IN ('wc-processing', 'wc-completed')
	AND oi2.meta_key = '_product_id'
	AND oi2.meta_value != %d
	AND EXISTS (
		SELECT 1
		FROM {$wpdb->prefix}woocommerce_order_items as oi3
		JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oi4 ON oi3.order_item_id = oi4.order_item_id
		WHERE oi3.order_id = {$wpdb->prefix}posts.ID
		AND oi4.meta_key = '_product_id'
		AND oi4.meta_value = %d
	)
	GROUP BY oi2.meta_value
	ORDER BY count DESC
	LIMIT 3
";

$results = $wpdb->get_results( $wpdb->prepare( $query, $product_id, $product_id ) );

return $results;
}
echo "<pre>", print_r( $list_top3_products ), "</pre>";

The output should look like this:

Array
(
    [0] => stdClass Object
        (
            [ID] => 9703
            [post_title] => Order – August 19, 2021 @ 01:02 AM
            [count] => 23
        )

    [1] => stdClass Object
        (
            [ID] => 10306
            [post_title] => Order – November 3, 2021 @ 01:57 PM
            [count] => 18
        )

    [2] => stdClass Object
        (
            [ID] => 9328
            [post_title] => Order – August 3, 2021 @ 12:54 PM
            [count] => 10
        )

)
^