Reputation: 777
With Woocommerce, this website has two types of buttons for products:
When clicked on "Contact us to order" button, visitors get redirected to a contact form in "Contact us to order" page. This contact form is built with Contact form 7 plugin.
For some of the products, the contact form has an exclusive checkbox field where they get to choose the lining. Based on which lining they chose, I am redirecting the visitors to the checkout page with some value passed through the URL.
For example: https://milanshopping.co.uk/checkout/?val=15
And in the functions.php
file, I am using the following code:
add_action( 'woocommerce_cart_calculate_fees','milanshopping_add_lining_fees' );
function milanshopping_add_lining_fees() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if(isset($_GET['val'])){
if($_GET['val'] == 15){
$leather_fee = 15;
}else{
$leather_fee = 20;
}
}
if($leather_fee != 0 ){
WC()->cart->add_fee( 'Leather fee', $leather_fee);
}
}
But this fails to add the fee even though the $_GET
value is present. I have checked by calling the echo $_GET['val']
and the value is printed.
But if I add the following code outside the if statement,
WC()->cart->add_fee( 'Leather fee', $leather_fee);
it works though fee added is 0 and not the fees I am trying to generate from the $_GET
value. Any idea?
Redirection from contact us to order page to checkout page is done using the Contact form 7 dom event "wpcf7submit" and products are added to cart using a separate function.
Upvotes: 1
Views: 733
Reputation: 253919
Updated: You need to grab the queried url variable value in sessions first, this way:
add_action( 'template_redirect', 'grab_fee_query_var' );
function grab_fee_query_var() {
session_start();
// Not on checkout page
if( ! is_admin() && isset($_GET['val']) ) {
$_SESSION['leather_fee'] = $_GET['val'];
WC()->session->__unset('leather_fee');
}
}
add_action( 'woocommerce_cart_calculate_fees','add_custom_cart_fee' );
function add_custom_cart_fee() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if(isset($_SESSION['leather_fee']) && ! WC()->session->__isset('leather_fee') ){
$value = $_SESSION['leather_fee'] == 15 ? 15 : 20;
WC()->session->set('leather_fee', $value );
}
if( WC()->session->__isset('leather_fee') ) {
$leather_fee = WC()->session->get('leather_fee');
WC()->cart->add_fee( 'Leather fee', $leather_fee);
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 1