Created
June 29, 2021 10:51
-
-
Save plugin-republic/f830b3ac797abf9cd5a0a5355f35c714 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check if there are any out of stock child products in the cart | |
* Remove the parent product if so | |
*/ | |
function prefix_woocommerce_check_cart_items() { | |
// If we've enabled the check | |
foreach( WC()->cart->cart_contents as $cart_item_key=>$cart_item ) { | |
if( ! empty( $cart_item['product_extras']['products']['child_products'] ) ) { | |
// This is a parent product so we might need to check that the child products are still in stock | |
foreach( $cart_item['product_extras']['products']['child_products'] as $child_product_id=>$data ) { | |
// Iterate through each child product and check its stock level | |
if( apply_filters( 'pewc_check_child_product_stock', false, $child_product_id ) ) { | |
$child_product = wc_get_product( $child_product_id ); | |
if( ! $child_product->is_in_stock() ) { | |
// Check whether it's still in stock and if we need to prevent purchasing the parent product | |
wc_add_notice( | |
apply_filters( | |
'pewc_child_product_out_of_stock_message', | |
__( 'One of the options in this order is out of stock so the product has been removed from the cart', 'pewc' ) | |
), | |
'error' | |
); | |
// Remove the main product from the cart | |
WC()->cart->remove_cart_item( $cart_item_key ); | |
} | |
} | |
} | |
} | |
} | |
}; | |
add_action( 'woocommerce_check_cart_items', 'prefix_woocommerce_check_cart_items', 10 ); | |
add_filter( 'pewc_check_child_product_stock', '__return_true' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment