Home / eCommerce / ACFW – Invalidate coupons for products with certain custom meta data
Duplicate Snippet

Embed Snippet on Your Site

ACFW – Invalidate coupons for products with certain custom meta data

Code Preview
php
<?php
  add_filter( 'woocommerce_coupon_is_valid', function( $valid, $coupon, $discount ) {
      $excluded_channels = $coupon->get_meta( '_excluded_og_channels', true );
      if ( empty( $excluded_channels ) ) {
          return $valid;
      }
      // Handle both a single stored string and a serialized array
      if ( ! is_array( $excluded_channels ) ) {
          $excluded_channels = array( $excluded_channels );
      }
      foreach ( WC()->cart->get_cart() as $cart_item ) {
          $product_id = ! empty( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
          $og_channel = get_post_meta( $product_id, 'og_channel', true );
          if ( empty( $og_channel ) && ! empty( $cart_item['variation_id'] ) ) {
              $og_channel = get_post_meta( $cart_item['product_id'], 'og_channel', true );
          }
          if ( $og_channel && in_array( $og_channel, $excluded_channels, true ) ) {
              throw new Exception(
                  __( 'Sorry, this coupon is not valid for one or more products in your cart.', 'woocommerce' )
              );
          }
      }
      return $valid;
  }, 10, 3 );

Comments

Add a Comment