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 clifgriffin/00087b47b2a1b4021beb43ee596dc4df to your computer and use it in GitHub Desktop.
Save clifgriffin/00087b47b2a1b4021beb43ee596dc4df to your computer and use it in GitHub Desktop.
In CheckoutWC's Delivery method, hide the Shipping option completely when at least one product in the cart is assigned to a specific category.
<?php
/*
* In CheckoutWC's Delivery method, hide the Shipping option completely when at least
* one product in the cart is assigned to a specific category.
*
* @author Obi Juan <hola@obijuan.dev>
* @link https://obijuan.dev
*/
/*
* Check if a product in the cart belongs to a specific category.
*
* @param string $category_slug The slug of the category.
* @return boolean True if at least one product in the cart belongs to the category, false otherwise.
*/
function is_product_of_category_in_cart( $category_slug ) {
// Check if the cart exists and is not empty
if ( WC()->cart && !WC()->cart->is_empty() ) {
// Loop through all cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Get the product object from the cart item
$product = $cart_item['data'];
/*
* Add support for variable products.
* Variations in variable products do not have categories.
* So, we need to identify if we are checking a variation or a simple product.
* If it is a variation, then get the parent product ID and check its category.
*
* @contributor Wojtek Hoch
*/
// Determine the ID to check based on product type!
if ($product->get_type() == 'variation') {
// For variations, get the parent product's ID!
$checked_product_id = $product->get_parent_id();
} else {
// For simple products, get the product's own ID!
$checked_product_id = $product->get_id();
}
// Check if product belongs to the specified category
if ( has_term( $category_slug, 'product_cat', $product->get_id() ) ) {
// If the product is in the specified category, return true
return true;
}
}
}
// If no product in the specified category is found in the cart, return false
return false;
}
/*
* Implementation.
*
* @filter cfw_local_pickup_disable_shipping_option
* @$category The category slug. E.g. "Cat 1" > "cat-1".
* @return boolean to either enable or disable the Shipping option.
*/
add_filter('cfw_local_pickup_disable_shipping_option', function(){
$category = 'cat-1'; // Category slug.
return is_product_of_category_in_cart($category); // True or False.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment