You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助更新WooCommerce购物车代码:旧代码在PHP7及新版WooCommerce失效

Fixing WooCommerce Cart Code for Modern Versions

Hey there! The code you're using relies on the old global $woocommerce approach, which has been phased out in newer WooCommerce releases (especially paired with PHP 7+). Let's update it to use WooCommerce's current recommended methods, which are more reliable and future-proof.

Updated Working Code

Here's the revised version that should play nice with recent WooCommerce versions:

// Get the WooCommerce cart instance (replaces the old global $woocommerce)
$cart = WC()->cart;

// Debug: Check if we can access the cart properly
var_dump($cart);

// Only proceed if the cart exists
if (isset($cart)) {
    // Empty the current cart
    $cart->empty_cart();
    
    // Validate and get the product ID from the URL parameter
    $product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;
    
    if ($product_id > 0) {
        // Add the product to cart (default quantity is 1; add a 2nd parameter to change it, e.g., 2)
        $add_result = $cart->add_to_cart($product_id);
        
        // Debug: Check if the product was added successfully
        var_dump($add_result ? "Product added to cart!" : "Failed to add product");
        var_dump($cart);
    } else {
        echo "Invalid product ID provided in the URL";
    }
} else {
    echo "WooCommerce cart isn't available right now — make sure this code runs after WooCommerce finishes loading";
}

Key Changes & Why They Matter

  • Swapped global $woocommerce for WC()->cart: WooCommerce now recommends using the WC() singleton function to access core objects. This avoids scope issues and ensures you're always getting a properly initialized cart instance.
  • Added product_id validation: Directly using $_GET['product_id'] is risky (it could be empty or malicious), so we convert it to an integer and check it's a valid positive number first.
  • Added cart existence check: Prevents errors if your code runs too early (before WooCommerce has fully loaded its core components).
  • Added success check for add_to_cart: The method returns a value indicating whether the product was added, so we can use that to debug issues quickly.

Quick Tips

  • Make sure this code runs after WooCommerce initializes. If you're using it in a custom template or plugin, hook it to actions like woocommerce_init or template_redirect to avoid "cart not found" errors.
  • For extra security, add a nonce check if this code is triggered by user actions (to prevent unauthorized requests).

内容的提问来源于stack exchange,提问作者François Audras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:28:53