Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // a function to check if the cart has product from CATEGORY and it's subcategory id
- function cart_has_product_from_CATEGORY() {
- //Check to see if user has product in cart
- global $woocommerce;
- //assigns a default negative value
- $product_in_cart = false;
- // start of the loop that fetches the cart items
- foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
- $_product = $values['data'];
- $terms = get_the_terms( $_product->id, 'product_cat' );
- // second level loop search, in case some items have several categories
- if($terms){
- foreach ($terms as $term) {
- $_categoryid = $term->term_id;
- if (( $_categoryid === PRODUCT_CAT_ID) ) {
- //category is in cart!
- $product_in_cart = true;
- }
- }
- }
- }
- return $product_in_cart;
- }
- // add filter and function to hide method
- add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' , 10, 1 );
- add_filter( 'woocommerce_package_rates', 'custom_shipping_methods', 100, 2 );
- function custom_shipping_methods( $rates, $package ){
- // Define/replace here your correct category slug (!)
- $cat_slug = PRODUCT_CAT_SLUG;
- $prod_cat = false;
- // Going through each item in cart to see if there is anyone of your category
- foreach ( WC()->cart->get_cart() as $values ) {
- $product = $values['data'];
- // compatibility with WC +3
- $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
- if ( has_term( $cat_slug, 'product_cat', $product_id ) )
- $prod_cat = true;
- }
- $rates_arr = array();
- if ( $prod_cat ) {
- foreach( $rates as $rate_id => $rate ) {
- //change to live store IDs
- if ( FLAT_RATE_METHOD_ID === $rate->instance_id || FLAT_RATE_METHOD_ID === $rate->instance_id ) {
- $rates_arr[ $rate_id ] = $rate;
- }
- }
- }
- return !empty( $rates_arr ) ? $rates_arr : $rates;
- }
- //Notify the client item can't be sent any other way
- add_action( 'woocommerce_before_checkout_form' , 'ib_product_notices' );
- add_action('woocommerce_before_cart_table','ib_product_notices');
- function ib_product_notices() {
- global $woocommerce;
- if( cart_has_product_from_CATEGORY()){
- wc_print_notice( "NOTICE HERE", $notice_type = 'notice' );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement