Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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