Skip to content

Instantly share code, notes, and snippets.

@smeric
Forked from Katamo/gist:10243188
Last active September 16, 2023 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save smeric/3392aa23c0d63648c198ed1d5775e95c to your computer and use it in GitHub Desktop.
Save smeric/3392aa23c0d63648c198ed1d5775e95c to your computer and use it in GitHub Desktop.
Check if the WooCommerce cart contains virtual product
<?php
/**
* Check if the cart contains virtual product
*
* @return bool
*/
function woo_cart_has_virtual_product(){
global $woocommerce;
// By default, no virtual product
$has_virtual_products = false;
// Default virtual products number
$virtual_products = 0;
// Get all products in cart
$products = $woocommerce->cart->get_cart();
// Loop through cart products
foreach ( $products as $product ) {
// Get product variation ID or product ID
if ( $product['variation_id'] ){
$product_id = $product['variation_id'];
}
else {
$product_id = $product['product_id'];
}
$is_virtual = get_post_meta( $product_id, '_virtual', true );
// Update $has_virtual_product if product is virtual
if ( $is_virtual == 'yes' ){
$virtual_products += 1;
}
}
if ( count($products) == $virtual_products ){
$has_virtual_products = true;
}
return $has_virtual_products;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment