Home / eCommerce / WWPP – Exclude products from Cart Subtotal Price Discounts if they have an individual price or belong to a specific category
Duplicate Snippet

Embed Snippet on Your Site

WWPP – Exclude products from Cart Subtotal Price Discounts if they have an individual price or belong to a specific category

Code Preview
php
<?php
  /**
   * Recalculate the cart subtotal discount to exclude products that:
   * - belong to a specific product category e.g., 'music' , OR
   * - have an individual wholesale price set for the customer's role.
   */
  add_filter( 'wwpp_cart_subtotal_based_discount', 'wwpp_recalculate_discount_for_eligible_items' );
  function wwpp_recalculate_discount_for_eligible_items( $discount ) {
      global $wc_wholesale_prices;
      $cart = WC()->cart;
      if ( ! $cart ) {
          return $discount;
      }
      $wholesale_role = $wc_wholesale_prices->wwp_wholesale_roles->getUserWholesaleRole();
      if ( empty( $wholesale_role ) ) {
          return $discount;
      }
      // Build eligible subtotal, skipping excluded products.
      $eligible_subtotal = 0.0;
      foreach ( $cart->get_cart() as $cart_item ) {
          $product_id   = $cart_item['product_id'];
          $variation_id = $cart_item['variation_id'] ?? 0;
          $id_to_check  = $variation_id > 0 ? $variation_id : $product_id;
          // Exclude: a specific category e.g., 'music'.
          if ( has_term( 'music', 'product_cat', $product_id ) ) {
              continue;
          }
          // Exclude: product has an individual wholesale price for this role.
          $individual_price = get_post_meta( $id_to_check, $wholesale_role[0] . '_wholesale_price', true );
          if ( ! empty( $individual_price ) ) {
              continue;
          }
          $eligible_subtotal += (float) $cart_item['line_total'];
      }
      // Recalculate discount against the eligible subtotal only.
      $discount_mapping = get_option( 'wwpp_option_wholesale_role_cart_subtotal_price_based_discount_mapping', array() );
      // Sort descending by threshold so the highest qualifying rule matches first.
      usort( $discount_mapping, fn( $a, $b ) => $b['subtotal_price'] <=> $a['subtotal_price'] );
      $new_amount = 0.0;
      foreach ( $discount_mapping as $mapping ) {
          if ( $mapping['wholesale_role'] !== $wholesale_role[0] ) {
              continue;
          }
          if ( $eligible_subtotal >= (float) $mapping['subtotal_price'] ) {
              $new_amount = 'percent-discount' === $mapping['discount_type']
                  ? $eligible_subtotal * ( (float) $mapping['discount_amount'] / 100 )
                  : (float) $mapping['discount_amount'];
              break;
          }
      }
      $discount['discount_amount'] = $new_amount;
      return $discount;
  }

Comments

Add a Comment