如何在WordPress的全局变量中存储数据?

时间:2018-08-01 10:44:27

标签: php jquery ajax wordpress

我正在WordPress中创建一个插件,该插件可让我的客户将产品添加到捆绑包中,然后将这些产品添加到购物车中。我通过jquery中的ajax将产品ID发送到php函数,然后该函数增加数组中该产品的数量。 到目前为止,这是我的代码:

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);
   }
});

问题是,当我在函数内调用add_product_to_bundle时,quantity设置为1,但是当我在add_bundle中使用全局变量($ args)时,{{1} }仍为0。我也尝试过使用quantity,但得到的结果相同。 如何保存在$_SESSION内部所做的更改? 谢谢!

0 个答案:

没有答案