skip to Main Content

I want to store Google Adwords gclid parameter to Woocommerce Database. Any idea how can I do this. I want to create a new field in the Woocommerce orders to store the gclid if its present.

Onclick place order button, I want to store the gclid into woocommerce order(database and backend) if its present.

2

Answers


  1. Chosen as BEST ANSWER

    I have done this with below code:

    // Adding Google Adwords gclid parameter to Woocommerce Database
    add_action( 'init', 'gclid_session' );
    function gclid_session () {
        // Early initialize customer session
        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true );
        }
        if ( isset( $_GET['gclid'] ) ) {
            $gclid_ide = isset( $_GET['gclid'] )  ? esc_attr( $_GET['gclid'] )  : '';
            // Set the session data
            WC()->session->set( 'gclid_id', $gclid_ide );
        }
    }
    
    // Save session data as order meta data
    add_action( 'woocommerce_checkout_create_order', 'set_order_gclid_meta' );
    function set_order_gclid_meta( $order ) {
        $gclid_ide = WC()->session->get( 'gclid_id' ); // Get custom data from session
        if ( isset($gclid_ide) ) {
            $order->update_meta_data( '_gclid', $gclid_ide );
        }    
        WC()->session->__unset( 'gclid_id' ); // Remove session variable
    }
    
    // Show this session variables in new order email for admin and in woocommerce order page
    // add_action( 'woocommerce_email_after_order_table', 'show_gclid_data', 20 );
    add_action( 'woocommerce_admin_order_data_after_billing_address', 'show_gclid_data' );
    function show_gclid_data( $order ) {
        if ( $id_gclid = $order->get_meta( '_gclid' ) )
            echo '<p><strong>gclid :</strong> ' . $id_gclid . '</p>';
    }
    

  2. I would store the gclid in WooCommerce session storage (you can check on each page load if the gclid is set in URL and doesn’t exist yet in WC session storage) like this:

    add_action( 'init', 'set_gclid_wc_session' );
    function set_gclid_wc_session() {
    
        $gclid_value = $_GET['gclid'] ?? null;
        if( $gclid_value ) {
            WC()->session->set( 'gclid', $gclid_value );
        }
    }
    

    Then, you can store the gclid as an order meta after it is created like this:

    add_action( 'woocommerce_checkout_create_order', 'set_order_gclid_meta', 20, 2 );
    function set_order_gclid_meta( $order, $data ) {
        $gclid = WC()->session->get( 'gclid' );
        if( $gclid ) {
            $order->update_meta_data( '_gclid', 'value' );
        }
    }
    

    Then you can do anything you want with this meta (display in in the dashboard, etc.).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search