Reputation: 439
I need to pass a product ID that is stored as var inside a filter to another function.
I tried this and it doesn't pass the ID:
PHP
$has_option_id = null;
function wc_add_to_cart_message_filter($message, $product_id = null) {
$GLOBALS['has_option_id'] = $product_id;
return $message;
}
add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );
function above_cart_js() {
$product_id = $GLOBALS['has_option_id'];
echo $product_id; // Outputs NULL (nothing)
}
add_action ( 'woocommerce_before_cart', 'above_cart_js', 5 );
Is there a way to pass the ID to the other function?
Upvotes: 0
Views: 107
Reputation: 3572
As your given action and filter don't runt at the same HTTP request, they can't global variable to each other. One of them is usually run by AJAX, another in is just Cart Template Hook. So, you can do it by Cookie Storage. First store just added product ID to Cookie, then get it from there.
function wc_add_to_cart_message_filter($message, $product_id = null) {
setcookie('just_added_product', array_keys($product_id)[0], time() + (600), "/");
return $message;
}
add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_filter', 10, 2 );
function above_cart_js() {
echo $_COOKIE["just_added_product"];
}
add_action ( 'woocommerce_before_cart', 'above_cart_js', 5 );
Upvotes: 1