vapvarun

Gravity form pre populate hidden fields

Nov 1st, 2021 (edited)
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. add_filter( 'gform_pre_render_2', 'newchip_gform_pre_render' );
  2. function newchip_gform_pre_render( $form ) {
  3.     $form_id = $form['id'];
  4.     if ( empty( $_POST[ 'is_submit_' . $form_id ] ) && class_exists( 'WooCommerce' ) ) {
  5.         $order_statuses = array('wc-on-hold', 'wc-processing', 'wc-completed');    
  6.         $customer_user_id = get_current_user_id(); // current user ID here for example
  7.         // Getting current customer orders
  8.         $customer_orders = wc_get_orders( array(
  9.             'meta_key' => '_customer_user',
  10.             'meta_value' => $customer_user_id,
  11.             'post_status' => $order_statuses,
  12.             'numberposts' => 1
  13.         ) );
  14.        
  15.         foreach($customer_orders as $order ){
  16.  
  17.             // Order ID (added WooCommerce 3+ compatibility)
  18.             $order_created_date = $order->get_date_created();          
  19.             $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
  20.  
  21.             // Iterating through current orders items
  22.             foreach($order->get_items() as $item_id => $item){
  23.                 $product_name = method_exists( $item, 'get_name' ) ? $item->get_name() : $item['name'];
  24.             }
  25.         }
  26.         foreach ( $form['fields'] as &$field ) {
  27.             if ( $field->id == 6 ) {
  28.                 $field->defaultValue = $product_name;
  29.             }
  30.             if ( $field->id == 7 ) {
  31.                 $field->defaultValue = $order_created_date;
  32.             }
  33.         }
  34.        
  35.     }
  36.     return $form;
  37. }
Add Comment
Please, Sign In to add comment