Skip to content

Instantly share code, notes, and snippets.

@claygriffiths
Last active July 10, 2023 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save claygriffiths/4eba8b2f2f1be92f9bd0e19875c7dea8 to your computer and use it in GitHub Desktop.
Save claygriffiths/4eba8b2f2f1be92f9bd0e19875c7dea8 to your computer and use it in GitHub Desktop.
GS Product Configurator: Populate Field with Order ID
<?php
/**
* Gravity Shop // GS Product Configurator // Populate Gravity Forms field with WooCommerce Order ID
*
* Populate fields in a Gravity Form that is linked to a WooCommerce product using GS Product Configurator
* with the WooCommerce order ID after checking out.
*
* Credit: Rochelle Victor (https://github.com/rochekaid)
*
* Instructions:
* 1. Install per https://gravitywiz.com/documentation/how-do-i-install-a-snippet/
* 2. Add the CSS class "wc_gf_order_id" to any field in your Gravity Form that you want to populate with the
* WooCommerce order ID.
*/
add_action( 'woocommerce_checkout_order_processed', function( $order_id ) {
if ( ! class_exists( '\GS_Product_Configurator\WC_Order_Item' ) || ! class_exists( 'GFAPI' ) ) {
return;
}
$order = wc_get_order( $order_id );
/**
* @var string $field_css_class Any fields with this class will have its value replaced with the
* WooCommerce order ID.
*/
$field_css_class = 'wc_gf_order_id';
if ( ! $order ) {
return;
}
foreach ( $order->get_items() as $item ) {
$gspc_order_item = \GS_Product_Configurator\WC_Order_Item::from( $item );
foreach ( $gspc_order_item->get_entries() as $entry ) {
$form = GFAPI::get_form( $entry['form_id'] );
$entry_updated = false;
foreach ( $form['fields'] as $field ) {
$css_classes = empty( $field->cssClass ) ? [] : explode( ' ', $field->cssClass );
if ( ! in_array( $field_css_class, $css_classes, true ) ) {
continue;
}
$entry[ $field->id ] = $order->ID;
$entry_updated = true;
}
if ( $entry_updated ) {
GFAPI::update_entry( $entry );
}
}
}
} );
@rochekaid
Copy link

Clay, this is great!! I believe line 40 should be the following and then it works perfect:
$css_classes = empty( $field->cssClass ) ? [] : explode( ' ', $field->cssClass );

@claygriffiths
Copy link
Author

@rochekaid Fixed! Sorry about that. Could've sworn I fixed that 😆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment