dqrmkdu25623 2018-08-01 10:44
浏览 75

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

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!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 2024-五一综合模拟赛
    • ¥15 如何将下列的“无限压缩存储器”设计出来
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口