Skip to content

Instantly share code, notes, and snippets.

@dianewallace
Created November 20, 2020 17:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dianewallace/8b395a718c8dbcd7f9e0c70ca45c2ccb to your computer and use it in GitHub Desktop.
Save dianewallace/8b395a718c8dbcd7f9e0c70ca45c2ccb to your computer and use it in GitHub Desktop.
add_filter( 'woocommerce_product_get_stock_status', 'my_plugin_set_stock_status', 10, 2 );
add_filter( 'woocommerce_product_variation_get_stock_status', 'my_plugin_set_stock_status', 10, 2 );
/**
* Set maximum back orders.
*
* @param $stock_status string product stock status.
* @param $product integer product.
*
* @return mixed|string
*/
function my_plugin_set_stock_status( $stock_status, $product ) {
$numleft = $product->get_stock_quantity();
if($numleft <= -200) {
// out of stock
return is_admin() ? $stock_status : 'outofstock';
}
else if( -200 < $numleft && $numleft <= 0 ) {
return is_admin() ? $stock_status : 'onbackorder';
}
else {
return is_admin() ? $stock_status : 'instock';
}
}
add_action( 'woocommerce_checkout_before_order_review', 'my_plugin_out_of_stock_items' );
add_action( 'woocommerce_before_cart', 'my_plugin_out_of_stock_items' );
/**
* Remove out of stock items from cart.
*/
function my_plugin_out_of_stock_items() {
if ( WC()->cart->is_empty() ) {
return;
}
$removed_products = [];
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Get an instance of the WC_Product Object
$product = $cart_item['data'];
// Get stock quantity
$stock_qty = $product->get_stock_quantity();
// get cart item quantity
$item_qty = $cart_item['quantity'];
if ( ( $stock_qty - $item_qty ) < - 200 ) {
WC()->cart->remove_cart_item( $cart_item_key );
$removed_products[] = $product;
}
}
if ( ! empty( $removed_products ) ) {
//wc_clear_notices(); // remove any WC notice about sorry about out of stock products to be removed from cart.
foreach ( $removed_products as $idx => $product ) {
$product_name = $product->get_title();
$removed_products_msg = sprintf( __( "The product '%s' was removed from your cart because it is out of stock.", 'woocommerce' ), $product_name );
wc_add_notice( $removed_products_msg, 'error' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment