|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Gravity Perks // Limit Submissions // Dynamically Set Limit by User WooCommerce Product Purchase Count |
| 4 | + * https://gravitywiz.com/documentaiton/gravity-forms-limit-submissions/ |
| 5 | + * |
| 6 | + * Dynamically set the limit by how many times the current user has purchased a specific WooCommerce product. |
| 7 | + * This is useful when a user must complete a form once each time they purchase the product. |
| 8 | + * Note: This requires users to be logged in, so does not work for guest purchases. |
| 9 | + * |
| 10 | + * Instructions: |
| 11 | + * |
| 12 | + * 1. Install the snippet. |
| 13 | + * https://gravitywiz.com/documentation/managing-snippets/ |
| 14 | + * |
| 15 | + * 2. Configure the snippet based on inline instructions. |
| 16 | + */ |
| 17 | +// Update "123" to your form ID. |
| 18 | +add_filter( 'gpls_rule_groups_123', function ( $rule_groups ) { |
| 19 | + |
| 20 | + $target_product_id = 4; // Update "4" to your Woo product ID |
| 21 | + |
| 22 | + $current_user_id = get_current_user_id(); |
| 23 | + if ( ! $current_user_id ) { |
| 24 | + $rule_groups[0]->limit = 0; |
| 25 | + return $rule_groups; |
| 26 | + } |
| 27 | + |
| 28 | + $customer_orders = wc_get_orders( |
| 29 | + array( |
| 30 | + 'limit' => -1, |
| 31 | + 'status' => array( 'completed', 'processing' ), |
| 32 | + 'customer' => $current_user_id, |
| 33 | + ) |
| 34 | + ); |
| 35 | + |
| 36 | + $purchase_count = 0; |
| 37 | + foreach ( $customer_orders as $customer_order ) { |
| 38 | + $order = wc_get_order( $customer_order->get_id() ); |
| 39 | + $order_items = $order->get_items(); |
| 40 | + foreach ( $order_items as $item ) { |
| 41 | + $product_id = $item->get_product_id(); |
| 42 | + if ( (int) $item->get_product_id() === (int) $target_product_id ) { |
| 43 | + $purchase_count += absint( $item->get_quantity() ); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + $rule_groups[0]->limit = (int) $purchase_count; |
| 49 | + return $rule_groups; |
| 50 | +} ); |
0 commit comments