|
7 | 7 | * |
8 | 8 | * 1. Add a Calculated Product to your parent form. |
9 | 9 | * 2. Add your Nested Form field with the :total modifier. |
10 | | - * 3. Copy and paste this snippet into your theme's functions.php file. |
| 10 | + * 3. Optional: If you want to merge duplicates, assign 'true' to the $merge_duplicates variable. |
| 11 | + * 4. Copy and paste this snippet into your theme's functions.php file. |
11 | 12 | * |
12 | 13 | * Now the Calculated Product field on your parent form will be replaced with the products from each child entry. |
13 | 14 | */ |
14 | | -add_filter( 'gform_product_info', function( $product_info, $form, $entry ) { |
| 15 | +$merge_duplicates = false; |
| 16 | +add_filter( 'gform_product_info', function( $product_info, $form, $entry ) use ( $merge_duplicates ) { |
15 | 17 |
|
16 | 18 | foreach ( $form['fields'] as $field ) { |
17 | 19 |
|
|
52 | 54 |
|
53 | 55 | $_child_products[ "{$nested_form_field_id}.{$child_entry['id']}_{$child_field_id}" ] = $child_product; |
54 | 56 | } |
55 | | - $child_products = $child_products + $_child_products; |
| 57 | + |
| 58 | + if ( $merge_duplicates ) { |
| 59 | + // Loop through $_child_products and compare with $child_products. |
| 60 | + foreach ( $_child_products as $key => $_child_product ) { |
| 61 | + $match_found = false; |
| 62 | + |
| 63 | + foreach ( $child_products as &$child_product ) { |
| 64 | + // Check if the name and price match |
| 65 | + if ( $child_product['name'] == $_child_product['name'] && $child_product['price'] == $_child_product['price'] ) { |
| 66 | + $child_product['quantity'] += $_child_product['quantity']; |
| 67 | + |
| 68 | + $match_found = true; |
| 69 | + unset( $_child_products[ $key ] ); |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // If there are remaining products in $_child_products (after merging) or if we are not merging, add them to $child_products. |
| 77 | + if ( ! empty( $_child_products ) || ! $merge_duplicates ) { |
| 78 | + $child_products = array_merge( $child_products, $_child_products ); |
| 79 | + } |
56 | 80 | } |
57 | 81 | } |
58 | 82 |
|
|
0 commit comments