我从AJAX检索到的产品ID将产品添加到购物车,但由于某些原因,我无法将定制价格添加到添加到购物车的产品中.

我try 将产品ID添加为全局变量,以在其他函数中使用变量,但无法将乘积设置为0.这就是我的代码最终的样子.

JS:

<script>
 const selectedProductId = getProdVal(randomDegree);
  const isProductInCart = isProductAlreadyInCart(selectedProductId);

  if (!productAdded && !isProductInCart) {
    jQuery.ajax({
      url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
      type: 'POST',
      data: {
        action: 'add_product_to_cart',
        product_id: selectedProductId,
      },
      success: function(response) {
        console.log(response);
        productAdded = true;
        spinBtn.disabled = false;
      },
      error: function(error) {
        console.error(error);
        spinBtn.disabled = false;
      }
    });
    jQuery.ajax({
      url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
      type: 'POST',
      data: {
        action: 'custom_set_cart_item_price',
        product_id: selectedProductId,
      },
      success: function(response) {
        console.log(response);
      },
      error: function(error) {
        console.error(error);
      }
    });
  }
</script>

Php:

function add_product_to_cart()
{
  if (isset($_POST['product_id'])) {
    $product_id = intval($_POST['product_id']);
    if (!in_array($product_id, get_product_ids_from_cart())) {
      WC()->cart->add_to_cart($product_id, 1, 0, [], []);
    }
    echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
  } else {
    echo json_encode(array('success' => false, 'message' => 'Product ID is missing.'));
  }

  exit;
}
add_action('wp_ajax_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_nopriv_add_product_to_cart', 'add_product_to_cart');
add_action('wp_ajax_custom_set_cart_item_price', 'custom_set_cart_item_price');
add_action('wp_ajax_nopriv_custom_set_cart_item_price', 'custom_set_cart_item_price');
function custom_set_cart_item_price($cart) {
  if (isset($_POST['product_id'])) {
    $product_id = intval($_POST['product_id']);
    $custom_price = 0.00; 
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == $product_id) {
          
            $cart_item['data']->set_price($custom_price);
            $cart->cart_contents[$cart_item_key] = $cart_item;
        }
    }
  }
}
add_action('woocommerce_before_calculate_totals', 'custom_set_cart_item_price');

推荐答案

当您将产品添加到购物车时,方法add_to_cart()返回cart item key,下面我们将在woocommerce_before_calculate_totals挂钩中使用的WC_SESSION变量中设置购物车项目键,以检索正确的购物车项目以将其价格更改为零.

假设您的jQuery代码工作正常,并通过AJAX发送要添加的产品ID:

<script>
const selectedProductId = getProdVal(randomDegree);
const isProductInCart = isProductAlreadyInCart(selectedProductId);

if (!productAdded && !isProductInCart) {
    jQuery.ajax({
        url: <?php echo json_encode(admin_url('admin-ajax.php')) ?>,
        type: 'POST',
        data: {
            action: 'custom_add_to_cart', // <== Renamed
            product_id: selectedProductId,
        },
        success: function(response) {
            console.log(response);
            productAdded = true;
            spinBtn.disabled = false;
        },
        error: function(error) {
            console.error(error);
            spinBtn.disabled = false;
        }
    });
}
</script>

PHP:

add_action('wp_ajax_custom_add_to_cart', 'custom_add_to_cart');
add_action('wp_ajax_nopriv_custom_add_to_cart', 'custom_add_to_cart');
function custom_add_to_cart() {
    if (isset($_POST['product_id']) && $_POST['product_id'] > 0 ) {
        $product_id = intval($_POST['product_id']);

        if (!in_array($product_id, get_product_ids_from_cart())) {
            // Get previous added products (if any) from WC_Session variable
            $items_keys = (array) WC()->session->get('zero_price_items'); 
            
            $cart_item_key = WC()->cart->add_to_cart($product_id, 1); // Add product 
            $items_keys[$cart_item_key] = $product_id; // add the key to the array

            // Save cart item key in a WC_Session variable
            WC()->session->set('zero_price_items', $items_keys );

            echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
        } else {
            echo json_encode(array('success' => true, 'message' => 'Product already in cart.'));
        }
    } else {
        echo json_encode(array('success' => false, 'message' => 'Product ID is missing.'));
    }
    wp_die();
}

// Change cart item price
add_action('woocommerce_before_calculate_totals', 'custom_set_cart_item_price');
function custom_set_cart_item_price( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $items_keys = (array) WC()->session->get('zero_price_items'); // Get the WC_Session variable data

    // Loop through cart items
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        // Check if the product has been added via custom ajax
        if ( isset($items_keys[$cart_item_key]) && $items_keys[$cart_item_key] == $cart_item['product_id'] ) {
            $cart_item['data']->set_price(0);
        }
    }
}

// For mini cart displayed price
add_action( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 2 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {
    $items_keys = (array) WC()->session->get('zero_price_items'); // Get the WC_Session variable data

    // Check if the product has been added via custom ajax
    if ( isset($items_keys[$cart_item_key]) && $items_keys[$cart_item_key] == $cart_item['product_id'] ) {
        return wc_price( 0 );
    }
    return $price_html;
}

代码放在导览子主题的unctions.php文件中(或在插件中).应该能行得通.

Php相关问答推荐

p a/a/p的x路径 Select ,但不是p somethext a链接/a或某些文本/p>

Laravel:启动下载并同时在Blade 中显示Flash消息

未在moodle上运行的计划任务

如何优化-PHP 7.3.14+Laravel 6

MySQLi是否在事务错误时删除保存点(并且仅删除保存点)?

Mod_重写子目录中相应的php文件

不包括WooCommerce中单独销售的产品

使注册字段UserMeta值对于WooCommerce中的每个用户是唯一的

列出所有WooCommerce处理订单中的产品数量,SKU和品牌

laravel Eloquent 模型的问题

从 XAMPP 运行 shell 脚本时,意外标记(附近出现语法错误

WooCommerce 按产品运输插件:仅收取较高的运输费用

WordPress 分页无法正常工作

如何在 Phpunit 的静态提供程序中创建测试双打?

symfony/notifier + twig/inky-extra 在 dunglas/symfony-docker 中缺少 ext-xsl.

Xdebug 不会在断点处停止

php preg_match 验证 Tiktok 用户名

使用 RSA 2048 公钥验证 RSA PKCS#1v1.5 SHA 256 签名

Laravel Factory - 在单列中生成具有随机迭代量的假 json 数组数据

PHP获取根据辞职日期自动续订的合同终止日期