MichelH

WooCommerce Coupon Validation for WCFM Vendor Products based on Minimum and Maximum Spend

Apr 5th, 2023 (edited)
51
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.65 KB | Source Code | 0 0
  1. add_filter('woocommerce_coupon_is_valid', function($is_valid, $coupon, $obj) {
  2. $coupon_author = get_post_field( 'post_author', $coupon->get_id() );
  3. if(!wcfm_is_vendor($coupon_author)) return $is_valid;
  4. $object = $obj->get_object();
  5. $total_item_cost = 0;
  6. if ( is_a( $object, 'WC_Cart' ) ) {
  7. foreach ( wc()->cart->get_cart() as $cart_item ) {
  8. $product = wc_get_product( $cart_item['data']->get_id() );
  9. $vendor_id = wcfm_get_vendor_id_by_post( $product->get_id() );
  10. if ( $vendor_id && $vendor_id == $coupon_author) {
  11. $total_item_cost += $cart_item['line_subtotal'];
  12. if($object->display_prices_including_tax()) {
  13. $total_item_cost += $cart_item['line_subtotal_tax'];
  14. }
  15. }
  16. }
  17. } elseif ( is_a( $object, 'WC_Order' ) ) {
  18. $line_items = $object->get_items( 'line_item' );
  19. foreach($line_items as $item) {
  20. $line_item = new WC_Order_Item_Product($item);
  21. $product_id = $line_item->get_product_id();
  22. $vendor_id = wcfm_get_vendor_id_by_post($product_id);
  23. if ( $vendor_id && $vendor_id == $coupon_author) {
  24. $total_item_cost += $line_item->get_subtotal();
  25. if ( $object->get_prices_include_tax() ) {
  26. $total_item_cost += $line_item->get_subtotal_tax();
  27. }
  28. }
  29. }
  30. }
  31. if($coupon->get_minimum_amount() > 0 && $coupon->get_minimum_amount() > $total_item_cost ) {
  32. throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
  33. }
  34. if($coupon->get_maximum_amount() > 0 && $coupon->get_minimum_amount() < $total_item_cost ) {
  35. throw new Exception( sprintf( __( 'The maximum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_maximum_amount() ) ), 112 );
  36. }
  37. return $is_valid;
  38. }, 10, 3);
Advertisement
Comments
  • MichelH
    3 years
    # text 0.13 KB | 0 0
    1. This code will be applied when the product total amount is matching the coupon code of the vendor , not reading all the cart total amount
Add Comment
Please, Sign In to add comment