Skip to content

Commit 72582cc

Browse files
committed
gpnf-child-products-in-parent-order-summary.php: Added support for child products in parent order summary.
1 parent a51989f commit 72582cc

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

gp-nested-forms/gpnf-child-products-in-parent-order-summary.php

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
*
88
* 1. Add a Calculated Product to your parent form.
99
* 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.
1112
*
1213
* Now the Calculated Product field on your parent form will be replaced with the products from each child entry.
1314
*/
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 ) {
1517

1618
foreach ( $form['fields'] as $field ) {
1719

@@ -52,7 +54,29 @@
5254

5355
$_child_products[ "{$nested_form_field_id}.{$child_entry['id']}_{$child_field_id}" ] = $child_product;
5456
}
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+
}
5680
}
5781
}
5882

0 commit comments

Comments
 (0)