Skip to content

Instantly share code, notes, and snippets.

@robertuniqid
Created June 23, 2015 09:48
Show Gist options
  • Save robertuniqid/f82c78169afac160efd5 to your computer and use it in GitHub Desktop.
Save robertuniqid/f82c78169afac160efd5 to your computer and use it in GitHub Desktop.
WooCommerce - Get Newest Order ID By UserID and Product ID
<?php
global $wpdb;
$query = 'SELECT oinfo.ID
FROM ' . $wpdb->base_prefix . 'woocommerce_order_items as oitem
LEFT JOIN ' . $wpdb->base_prefix . 'posts as oinfo ON oinfo.ID = oitem.order_id
LEFT JOIN ' . $wpdb->base_prefix . 'postmeta as ometa ON ometa.post_id = oinfo.ID AND ometa.meta_key = "_customer_user"
LEFT JOIN ' . $wpdb->base_prefix . 'woocommerce_order_itemmeta as oimeta ON oimeta.order_item_id = oitem.order_item_id
AND oimeta.meta_key = "_product_id"
AND oimeta.meta_value = ' . $product_id . '
WHERE ometa.meta_value=' . $user_id . ' ORDER BY oinfo.ID DESC';
@daigo75
Copy link

daigo75 commented Jun 24, 2015

Personally, I would write it this way. Table prefix is hard-coded, just because of laziness. :)

SELECT 
    ORDER_META.post_id AS order_id
FROM
    wp_postmeta ORDER_META
    JOIN
    woocommerce_order_items AS OI ON
        (OI.order_id = ORDER_META.post_id)
    JOIN
    wp_woocommerce_order_itemmeta AS OI_META ON
        (OI_META.order_item_id = OI.order_item_id) AND
        (OI_META.meta_key = '_product_id') AND
        (OI_META.meta_value = $product_id)
 WHERE
    (ORDER_META.meta_key = '_customer_user') AND
    (ORDER_META.meta_value = $user_id)
ORDER BY
    ORDER_META.post_ID DESC

Changes

  • Removed one unnecessary JOIN
  • Use INNER JOIN, rather than LEFT JOIN, as we don't need orders that don't match the criteria.

@robertuniqid
Copy link
Author

Personally, I would write it this way. Table prefix is hard-coded, just because of laziness. :)

SELECT 
    ORDER_META.post_id AS order_id
FROM
    wp_postmeta ORDER_META
    JOIN
    woocommerce_order_items AS OI ON
        (OI.order_id = ORDER_META.post_id)
    JOIN
    wp_woocommerce_order_itemmeta AS OI_META ON
        (OI_META.order_item_id = OI.order_item_id) AND
        (OI_META.meta_key = '_product_id') AND
        (OI_META.meta_value = $product_id)
 WHERE
    (ORDER_META.meta_key = '_customer_user') AND
    (ORDER_META.meta_value = $user_id)
ORDER BY
    ORDER_META.post_ID DESC

Changes

  • Removed one unnecessary JOIN
  • Use INNER JOIN, rather than LEFT JOIN, as we don't need orders that don't match the criteria.

Not sure how I haven't seen your reply until now :) great optimization, when I've coded this it was mostly for internal use, so I didn't go for speed optimizations.
I personally love left joins because they still work if the database is damaged for some reason, and the results are null.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment