Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugin-republic/f830b3ac797abf9cd5a0a5355f35c714 to your computer and use it in GitHub Desktop.
Save plugin-republic/f830b3ac797abf9cd5a0a5355f35c714 to your computer and use it in GitHub Desktop.
<?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