Skip to content

Instantly share code, notes, and snippets.

@coulterpeterson
Created August 24, 2023 14:45
Show Gist options
  • Save coulterpeterson/1a3359f0988913d8bbfb34ab6cc1257c to your computer and use it in GitHub Desktop.
Save coulterpeterson/1a3359f0988913d8bbfb34ab6cc1257c to your computer and use it in GitHub Desktop.
WooCommerce General Helper Functions
/**
* Determine if product ID is in cart. Returns true if so, false otherwise.
*/
function is_product_in_cart($product_id) {
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
$variation_in_cart = 0;
if( isset( $cart_item['variation_id'] ) ) {
$variation_in_cart = $cart_item['variation_id'];
}
if ( $product_in_cart === $product_id ) $in_cart = true;
if ( $variation_in_cart === $product_id ) $in_cart = true;
}
return $in_cart;
}
/**
* Returns an array of product IDs in cart.
*/
function get_cart_product_ids() {
$in_cart = array();
foreach( WC()->cart->get_cart() as $cart_item ) {
if( isset( $cart_item['variation_id'] ) ) {
array_push( $in_cart, $cart_item['variation_id'] );
} else {
array_push( $in_cart, $cart_item['product_id'] );
}
}
return $in_cart;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment