My goal is: allow customers to make no more than 60 pre-orders per day in a given time slot. The way I try to solve the problem is:
- when on checkout page, get amount of previously made orders via php and mysql. Pass it to js array
- user selects date, js compares it to a date in the array, checks the amount of products in a cart, adds
- shows an error message if total exceeds maximum
It seems to work correctly, except it counts all the products, though I need to limit the result to 1 category only. I tried for few hours to link it but with no success.
The main problem is that category info is stored in a table wp_termmeta/wp_terms and I can't understand how is it linked to the product ID or other columns that I currently use in the query.
SQL query:
SELECT REPLACE(a.meta_value,'-','') AS Date, SUM(c.meta_value) AS Quantity
FROM postmeta a, woocommerce_order_items b, woocommerce_order_itemmeta c
WHERE a.post_id = b.order_id AND b.order_item_id = c.order_item_id
AND b.order_item_type = 'line_item' AND a.meta_key='_deliverydate'
AND c.meta_key = '_qty' AND a.meta_value='$today'
My MySQL / PHP for the context that works:
add_action( 'wp_enqueue_scripts', 'menu_scripts' );
function menu_scripts() {
// Register the script
wp_register_script( 'custom_script', get_stylesheet_directory_uri() . '/script.js');
wp_enqueue_script( 'custom_script' );
$currenthour = date("H");
$today = date("Y-m-d");
$cartcount = WC()->cart->get_cart_contents_count();
$passphp = array(
'hour' => $currenthour,
'today' => $today,
'incart' => $cartcount
);
for($i=0;$i<61;$i++){
global $wpdb;
$prefix = $wpdb->prefix;
$result = $wpdb->get_results("
SELECT REPLACE(a.meta_value,'-','') AS Date, SUM(c.meta_value) AS Quantity
FROM ".$prefix."postmeta a, ".$prefix."woocommerce_order_items b,
".$prefix."woocommerce_order_itemmeta c
WHERE a.post_id = b.order_id AND b.order_item_id = c.order_item_id
AND b.order_item_type = 'line_item' AND a.meta_key='_deliverydate'
AND c.meta_key = '_qty' AND a.meta_value='$today'");
foreach($result as $row) {
$row->Date = str_replace("‐",",",$row->Date);
$passphp['x'.$row->Date] = $row->Quantity;
}
$today = date('Y-m-d', strtotime($today. ' + 1 days'));
}
// Localize the script with new data
wp_localize_script( 'custom_script', 'passphp' , $passphp);
}
Maybe there is some better workaround to achieve the goal I can't think of?
off-topic: I did try to use LEFT JOIN instead of query you see, but I am new to MySQL syntax and for now, given up breaking the code that works while trying to figure it out.