Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions gp-nested-forms/gpnf-child-products-in-parent-order-summary.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
*
* 1. Add a Calculated Product to your parent form.
* 2. Add your Nested Form field with the :total modifier.
* 3. Copy and paste this snippet into your theme's functions.php file.
* 3. Optional: If you want to merge duplicates, assign 'true' to the $merge_duplicates variable.
* 4. Copy and paste this snippet into your theme's functions.php file.
*
* Now the Calculated Product field on your parent form will be replaced with the products from each child entry.
*/
add_filter( 'gform_product_info', function( $product_info, $form, $entry ) {
$merge_duplicates = false;
add_filter( 'gform_product_info', function( $product_info, $form, $entry ) use ( $merge_duplicates ) {

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

Expand Down Expand Up @@ -52,7 +54,29 @@

$_child_products[ "{$nested_form_field_id}.{$child_entry['id']}_{$child_field_id}" ] = $child_product;
}
$child_products = $child_products + $_child_products;

if ( $merge_duplicates ) {
// Loop through $_child_products and compare with $child_products.
foreach ( $_child_products as $key => $_child_product ) {
$match_found = false;

foreach ( $child_products as &$child_product ) {
// Check if the name and price match
if ( $child_product['name'] == $_child_product['name'] && $child_product['price'] == $_child_product['price'] ) {
$child_product['quantity'] += $_child_product['quantity'];

$match_found = true;
unset( $_child_products[ $key ] );
break;
}
}
}
}

// If there are remaining products in $_child_products (after merging) or if we are not merging, add them to $child_products.
if ( ! empty( $_child_products ) || ! $merge_duplicates ) {
$child_products = array_merge( $child_products, $_child_products );
}
}
}

Expand Down
Loading