My products are added to the cart via the [wpv-woo-buy-or-select] shortcode contained within a view that lists all products related to the current post.
On the parent post page where the products view is shown I have a variable defined via a shortcode (below).
// Define Global Variable
if (isset($_GET["referrer"])) { // If Referrer is Set in URL Parameter
// Get Referrer User Id from URL Parameter
$referrerId = $_GET["referrer"];
} else { // Set store branding to product Vendor
$referrerId = get_the_author_meta('ID');
}
I have a custom product field "referrer-id".
When a customer adds a product to the cart, I need to save my global variable to the $cart_item_data (I think in the field "referrer-id") so that I can show who referred that user to the product.
I'm trying to achieve this using the code below...
/*
* Add referrer data to cart item.
*/
function add_referrer_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
global $rererrerId;
$cart_item_data['referrer-id'] = $rererrerId;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_referrer_to_cart_item', 10, 3 );
/*
* Display referrer info in the cart.
*/
function display_referrer_in_cart( $item_data, $cart_item ) {
if ( empty( $cart_item['referrer-id'] ) ) {
return $item_data;
}
$item_data[] = array(
'key' => __( 'Referrer' ),
'value' => wc_clean( $cart_item['referrer-id'] ),
'display' => '',
);
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_referrer_in_cart', 10, 2 );
The problem I have is that the variable doesn't appear to be being found by the function. In the Debug log I noticed that even if the global variable function appears before the other function in my function.php file, they output in the wrong order, so the global variable seems to be defined AFTER the function is executed, not before, meaning the function can't find the variable.
My understanding is limited here, but I suspect it's something to do with the [ wpv-woo-buy-or-select] shorcode template being called before the variable is defined?
Can you advise on what the issue may be and/or suggest a possible solution?