Advertisement
Barbareshet

Woocomerce Cart Manipulation, depending on product Category

Feb 27th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.05 KB | None | 0 0
  1. // a function to check if the cart has product from SOME CATEGORY and it's subcategory id
  2. function cart_has_product() {
  3.     //Check to see if user has product in cart
  4.     global $woocommerce;
  5.     //assigns a default negative value
  6.     $product_in_cart = false;
  7.  
  8.     // start of the loop that fetches the cart items
  9.     foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
  10.  
  11.         $_product = $values['data'];
  12.         $terms = get_the_terms( $_product->id, 'product_cat' );
  13.         // second level loop search, in case some items have several categories
  14.         if($terms){
  15.             foreach ($terms as $term) {
  16.                 $_categoryid = $term->term_id;
  17.                     //Add Cat Id here
  18.                 if (( $_categoryid === ( CAT_ID )|| $_categoryid === ( oTHER CAT_ID )) ) {
  19.                     //category is in cart!
  20.                     $product_in_cart = true;
  21.  
  22.                 }
  23.             }
  24.  
  25.         }
  26.     }
  27.     return $product_in_cart;
  28. }
  29.  
  30.  
  31.  
  32. function cange_product_notices(  ) {
  33.     global $woocommerce;
  34.     if( cart_has_product()){
  35.  
  36.         wc_print_notice( "CAN'T SEND BY MAIL THIS PRODUCT CATEGORY", $notice_type = 'error' );
  37.  
  38.         add_filter( 'woocommerce_shipping_methods', 'hide_shipping_method_for_CAT', 10, 2 );
  39.  
  40.  
  41.  
  42.  
  43.     }
  44. }
  45.  
  46. function hide_shipping_method_for_CAT( $rates, $package) {
  47.     // HERE set your product categories in the array (IDs, slugs or names)
  48.     $categories = array( CATEGORY NAME );
  49.     $found = false;
  50.     wp_die();
  51.     // Loop through each cart item Checking for the defined product categories
  52.     foreach( $package['contents'] as $cart_item ) {
  53.         if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
  54.  
  55.             $found = true;
  56.             break;
  57.         }
  58.     }
  59.  
  60.     $rates_arr = array();
  61.     if ( $found ) {
  62.         foreach($rates as $rate_id => $rate) {
  63.             if ('free_shipping' === $rate->method_id) {
  64.                 $rates_arr[ $rate_id ] = $rate;
  65.             }
  66.         }
  67.     }
  68.     return !empty( $rates_arr ) ? $rates_arr : $rates;
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement