Advertisement
verygoodplugins

Untitled

May 12th, 2025
411
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 1 0
  1. /**
  2.  * Validate applied coupon for guest users based on WPF contact tags.
  3.  */
  4. add_action( 'woocommerce_applied_coupon', 'wpf_validate_coupon_tag_access_for_guests' );
  5.  
  6. function wpf_validate_coupon_tag_access_for_guests( $coupon_code ) {
  7.  
  8.     if ( is_user_logged_in() ) {
  9.         // Let existing logged-in logic (if any) apply
  10.         return;
  11.     }
  12.  
  13.     // Get billing email from checkout session or posted field
  14.     $email = WC()->session->get( 'customer_email' );
  15.  
  16.     if ( empty( $email ) && ! empty( $_POST['billing_email'] ) ) {
  17.         $email = sanitize_email( wp_unslash( $_POST['billing_email'] ) );
  18.     }
  19.  
  20.     if ( empty( $email ) || ! is_email( $email ) ) {
  21.         return;
  22.     }
  23.  
  24.     // Attempt to get CRM contact ID
  25.     $contact_id = wp_fusion()->crm->get_contact_id( $email );
  26.  
  27.     if ( empty( $contact_id ) ) {
  28.         return;
  29.     }
  30.  
  31.     // Get contact's tags
  32.     $contact_tags = wp_fusion()->crm->get_tags( $contact_id );
  33.  
  34.     if ( empty( $contact_tags ) || ! is_array( $contact_tags ) ) {
  35.         $contact_tags = array();
  36.     }
  37.  
  38.     // Load coupon object
  39.     $coupon = new WC_Coupon( $coupon_code );
  40.  
  41.     if ( ! $coupon || ! $coupon->get_id() ) {
  42.         return;
  43.     }
  44.  
  45.     $coupon_id = $coupon->get_id();
  46.  
  47.     // Get access rules from WPF
  48.     $access_rules = wp_fusion()->access->get_post_access_meta( $coupon_id );
  49.  
  50.     if ( empty( $access_rules['allow_tags'] ) || ! is_array( $access_rules['allow_tags'] ) ) {
  51.         // No tag restrictions set on this coupon
  52.         return;
  53.     }
  54.  
  55.     $required_tags = $access_rules['allow_tags'];
  56.  
  57.     // Check if contact has any required tag
  58.     $has_required_tag = array_intersect( $required_tags, $contact_tags );
  59.  
  60.     if ( empty( $has_required_tag ) ) {
  61.  
  62.         WC()->cart->remove_coupon( $coupon_code );
  63.  
  64.         if ( ! wc_has_notice( $coupon_code . '_invalid_notice', 'error' ) ) {
  65.             /* translators: %s: coupon code */
  66.             wc_add_notice(
  67.                 sprintf(
  68.                     __( 'You do not have permission to use the coupon "%s".', 'wp-fusion' ),
  69.                     esc_html( $coupon_code )
  70.                 ),
  71.                 'error'
  72.             );
  73.         }
  74.     }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement