Thank you for reading my question. I believe my function could be useful to the community.
I am trying to sell products that I have in stock, but also allow backorders for the same and other products that my suppliers have in stock. I import the stock qty values for the 2x supplier locations into each product's custom fields using the Advanced Custom Fields and WP All Import Plugins.
I then use a maximum quantity plugin to limit how many items can be added to the cart to the combined value of all 3 stock fields. The goal is to not allow adding more to the cart than is available in total.
function backorder_autostock($post_id) {
$stockqty = get_post_meta($post_id, '_stock', true );
$autostocktotal = (get_field('autostock_cpt') + get_field('autostock_jhb'));
$maxstockqty = ($stockqty + $autostocktotal);
if ( get_field('autostock_enabled') == true && $autostocktotal > 0) {
update_post_meta($post_id,'_wc_max_qty_product', $maxstockqty);
update_post_meta($post_id,'_backorders', 'notify' );
update_field('autostock_total', $autostocktotal, $post_id);
}
else {
update_post_meta($post_id,'_backorders' , 'no' );
update_post_meta($post_id,'_wc_max_qty_product', '');
}
}
add_action('acf/save_post', 'backorder_autostock');
Its working pretty well, but I have 3 issues:
- $stockqty gets reduced when the order is placed, but $autostocktotal (backorder availibility qty) does not get reduced because it is not a native stock qty field.
Example: $stockqty = 1 and $autostocktotal = 6. Customer orders 2x items. Now $stockqty = 0 but $autostocktotal still = 6
The _wc_max_qty_product also does not get reduced so the maximum add to cart plugin still allows for all 7 units. (This is because of the function hook only triggering when the product is saved/updated, but not when a order is placed)
Even if I was able to solve the above issues, I will also need the quantities for products in pending orders to be reduced from future updated $stockqty and $autostocktotal values because the system that exports the values to update these fields will not be accurate if the orders are not processed yet.
Is there a practical way to get around the issues?
I have been all over the web looking for an out-of-box solution to just have a dedicated field that behaves like _stock , but just for backorder stock.