I'm creating a plugin in WordPress that lets my customers add products to a bundle and then add those products to a cart. I send product id's via ajax in jquery to a php function and then that function increments the quantity of that product in my array. Here is my code so far:
bundle.php
$args = array(
1 => array(
'product_id' => 2889,
'quantity' => 0,
),
2 => array(
'product_id' => 2964,
'quantity' => 0,
),
3 => array(
'product_id' => 2975,
'quantity' => 0,
),
4 => array(
'product_id' => 2974,
'quantity' => 0,
),
5 => array(
'product_id' => 2973,
'quantity' => 0,
),
6 => array(
'product_id' => 2972,
'quantity' => 0,
),
7 => array(
'product_id' => 2971,
'quantity' => 0,
),
8 => array(
'product_id' => 2970,
'quantity' => 0,
),
9 => array(
'product_id' => 2969,
'quantity' => 0,
),
10 => array(
'product_id' => 2966,
'quantity' => 0,
),
11 => array(
'product_id' => 2968,
'quantity' => 0,
),
12 => array(
'product_id' => 2965,
'quantity' => 0,
),
);
add_action('wp_ajax_add_bundle', 'add_bundle');
add_action('wp_ajax_nopriv_add_bundle', 'add_bundle');
function add_bundle() {
global $args;
$added = WC_PB()->cart->add_bundle_to_cart(3606, 1, $args);
exit();
}
add_action('wp_ajax_add_product_to_bundle', 'add_product_to_bundle');
add_action('wp_ajax_nopriv_add_product_to_bundle',
'add_product_to_bundle');
function add_product_to_bundle() {
$product_id = $_POST['variable'];
global $args;
$size = count($args);
for($i = 1; $i <= $size; $i++) {
if($args[$i]['product_id'] == $product_id) {
echo $args[$i]['quantity'];
$args[$i]['quantity'] = $args[$i]['quantity'] + 1;
echo $args[$i]['quantity'];
}
}
exit();
}
jquery_script.js
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'add_product_to_bundle',
variable: prod_id,
},
success: function (output) {
console.log(output);
}
});
The problem is when I call add_product_to_bundle
, quantity
is set to 1 inside the function, but when I use my global variable ($args) in add_bundle
, quantity
is still 0. I have tried with $_SESSION
too but I got the same result.
How can I keep changes made inside add_product_to_bundle
?
Thanks!