I currently have a wordpress site setup using woocommerce and gravity forms plugins. I am selling bike wheels and on my product page I use gravity forms to display different customization options. the options are different if they select one wheel or two wheels.
What I’m trying to achieve
I want to add a 5% discount if two wheels are selected and 10% if four+ are selected. This discount is applied to the product as it is added to the cart.
I am attempting to create a custom plugin that uses javascript to get the value from the gravity forms input, and hooks into woocommerce to edit the total price before adding it to the cart.
What I have so far
custom.js
jQuery(document).ready(function () {
jQuery('.cart').submit(function () {
var noOfWheels = jQuery(".rdoWheel input[type='radio']:checked").val();
console.log(noOfWheels)
var data = {
action: 'my_discount',
wheels: noOfWheels
};
jQuery.ajax({
type: 'POST',
url: discountAjax.ajax_url,
data: data,
success: function (data) {
//do nothing
},
});
return false;
});
});
discount.php
add_action('wp_enqueue_scripts', 'load_script');
function load_script() {
wp_enqueue_script('discount', plugin_dir_url( __FILE__ ) . 'custom/custom.js', array( 'jquery' ) );
wp_localize_script('discount', 'discountAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_ajax_woocommerce_discount', 'calculate', 10);
add_action('wp_ajax_nopriv_woocommerce_discount', 'calculate', 10);
function calculate() {
if (isset($_POST['wheels'])) {
global $woocommerce;
$wheels = $_POST['wheels'];
if ($wheels === "1") {
$val = 0;
} elseif ($wheels === "2"){
$val = 10;
}
session_start();
$_SESSION['val'] = $val;
}
}
add_action('woocommerce_before_calculate_totals', 'add_discount');
function add_discount( $cart_object) {
@session_start();
if (isset($_SESSION['val'])) {
$wheels = $_SESSION['val'];
foreach ( $cart_object->cart_contents as $key => $value ) {
$c_price = $value['data']->price;
$discountAmount = $c_price * $wheels/100;
$value['data']->price = $value['data']->price - $discountAmount;
}
//for testing purpose
echo $_SESSION['val'];
echo 'completed';
unset($_SESSION['val']);
}
}
whats happening
It seems the woocommerce function is not firing at all. when i check with firebug I see my ajax request go through okay then nothing else. If i remove everything except for the add_discount function then it goes through and applies the discount. I cant seem to get it to work with javascript/ajax.