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

因DHL插件致Add to cart缓慢,修复后出现WooCommerce警告求助

解决WooCommerce后台警告问题

问题原因

警告出现是因为WooCommerce后台部分场景下,WC()->cart对象还未被初始化,此时直接访问其prevent_recalc_on_add_to_cart属性就会触发"Attempt to read property on null"的警告。

修改后的代码

把原来添加的代码替换为以下内容:

/*
Remove recalculation of the shipping cost when Add-to-Cart. This prevents slow add-to-cart.
*/
function filter_need_shipping ($val) {
    // 先检查购物车对象是否存在
    if ( ! WC()->cart ) {
        return $val;
    }
    $prevent_after_add = WC()->cart->prevent_recalc_on_add_to_cart;
    return $val && !$prevent_after_add;
}
add_filter( 'woocommerce_cart_needs_shipping', 'filter_need_shipping' );

function mark_cart_not_to_recalc ($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
    // 先检查购物车对象是否存在
    if ( WC()->cart ) {
        WC()->cart->prevent_recalc_on_add_to_cart = true;
    }
}
add_action('woocommerce_add_to_cart', 'mark_cart_not_to_recalc', 10, 6);

修改说明

  • 在filter_need_shipping函数中增加WC()->cart的非空判断,若购物车对象不存在则直接返回原始值,避免触发警告。
  • 在mark_cart_not_to_recalc函数中同样增加非空判断,确保只有购物车对象存在时才设置属性。

修改后既保留了原代码优化Add to cart速度的功能,又能消除后台警告。

内容的提问来源于stack exchange,提问作者Wonder In Wonderland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:35:22