I currently have a custom code that gives me the ids of all the orders and it works well. (This code gives you the ID of a product and gives you all the orders for the product.)
This is:
function get_orders_ids_by_product_id( $product_id, $order_status = ['wc-completed', 'wc-processing'] ){
global $wpdb;
$results = $wpdb->get_col("
SELECT order_items.order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE posts.post_type = 'shop_order'
AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_product_id'
AND order_item_meta.meta_value = '$product_id'
");
return count($results);
}
However I need to filter the orders that were placed in a range of 0 to 4 hours maximum. I tried putting this in the query but was unsuccessful.
WHERE post_date < DATE_SUB(CURDATE(),INTERVAL 4 HOUR)
Code not working
function get_orders_ids_by_product_id( $product_id, $order_status = ['wc-completed', 'wc-processing'] ){
global $wpdb;
$results = $wpdb->get_col("
SELECT order_items.order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE posts.post_type = 'shop_order'
WHERE post_date < DATE_SUB(CURDATE(),INTERVAL 4 HOUR)
AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_product_id'
AND order_item_meta.meta_value = '$product_id'
");
return count($results);
}
What am I doing wrong?
It looks like the issue is happens because of incorrect placement of Where clause and usage of post_date
column.
I suggest you to use DATE_SUB(NOW(), INTERVAL 4 HOUR)
with the help of that we can subtracts 4 hours
from the current date and time
, which will gives you a date time that is 4 hours
ago from now, so could you please update the value of $result
in your code, it should work for you.
$results = $wpdb->get_col("
SELECT order_items.order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE posts.post_type = 'shop_order'
AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_product_id'
AND order_item_meta.meta_value = '$product_id'
AND posts.post_date >= DATE_SUB(NOW(), INTERVAL 4 HOUR)
");