Adding custom data to wordpress customer order

I need to capture a variable for tracking referers from an incoming URL and append it to an order in wordpress/woocommerce. Currently in the themes header.php file I have:

    if(!empty($_GET['refID'])) $_SESSION['refID'] = $_GET['refID'];

Then, in my themes functions.php file I have:

Read More
    if(!empty($_SESSION['refID'])) $rID = $_SESSION['refID'];
    else $rID = "no var set";

    add_action( 'woocommerce_checkout_update_order_meta', 'my_add_order_meta', 10, 2 );
    function my_add_order_meta( $order_id, $rID ) {
        update_post_meta( $order_id, 'refID', $rID );
    }

The session variable appears in the WP session, but nothing appears in the order after its posted. I have very little experience working with WP/woocommerce and would like to know if this is even the proper method for doing this?

Related posts

2 comments

  1. You’re setting the session variable, but aren’t using it…I believe your function should look more like the following:

    add_action( 'woocommerce_checkout_update_order_meta', 'my_add_order_meta' );
    function my_add_order_meta( $order_id ) {
        // Get the stored refID
        $refID = isset( $_SESSION['refID'] ) ? $_SESSION['refID'] : null;
        // Update the refID meta
        update_post_meta( $order_id, 'refID', $refID );
    }
    
  2. For some unknown reason, the variable wasn’t being passed from the session to $rID. By using the actual session variable the function is now posting the additional data to the order. I have also substituted $rID for $posted in the function call:

        add_action( 'woocommerce_checkout_update_order_meta', 'my_add_order_meta', 10, 2 ); 
        function my_add_order_meta( $order_id, $posted ) {
        update_post_meta($order_id, 'refID', $_SESSION['refID']);   
        }
    

Comments are closed.