Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Validate applied coupon for guest users based on WPF contact tags.
- */
- add_action( 'woocommerce_applied_coupon', 'wpf_validate_coupon_tag_access_for_guests' );
- function wpf_validate_coupon_tag_access_for_guests( $coupon_code ) {
- if ( is_user_logged_in() ) {
- // Let existing logged-in logic (if any) apply
- return;
- }
- // Get billing email from checkout session or posted field
- $email = WC()->session->get( 'customer_email' );
- if ( empty( $email ) && ! empty( $_POST['billing_email'] ) ) {
- $email = sanitize_email( wp_unslash( $_POST['billing_email'] ) );
- }
- if ( empty( $email ) || ! is_email( $email ) ) {
- return;
- }
- // Attempt to get CRM contact ID
- $contact_id = wp_fusion()->crm->get_contact_id( $email );
- if ( empty( $contact_id ) ) {
- return;
- }
- // Get contact's tags
- $contact_tags = wp_fusion()->crm->get_tags( $contact_id );
- if ( empty( $contact_tags ) || ! is_array( $contact_tags ) ) {
- $contact_tags = array();
- }
- // Load coupon object
- $coupon = new WC_Coupon( $coupon_code );
- if ( ! $coupon || ! $coupon->get_id() ) {
- return;
- }
- $coupon_id = $coupon->get_id();
- // Get access rules from WPF
- $access_rules = wp_fusion()->access->get_post_access_meta( $coupon_id );
- if ( empty( $access_rules['allow_tags'] ) || ! is_array( $access_rules['allow_tags'] ) ) {
- // No tag restrictions set on this coupon
- return;
- }
- $required_tags = $access_rules['allow_tags'];
- // Check if contact has any required tag
- $has_required_tag = array_intersect( $required_tags, $contact_tags );
- if ( empty( $has_required_tag ) ) {
- WC()->cart->remove_coupon( $coupon_code );
- if ( ! wc_has_notice( $coupon_code . '_invalid_notice', 'error' ) ) {
- /* translators: %s: coupon code */
- wc_add_notice(
- sprintf(
- __( 'You do not have permission to use the coupon "%s".', 'wp-fusion' ),
- esc_html( $coupon_code )
- ),
- 'error'
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement