未捕获的错误:在 null 上调用成员函数 is_empty() - 添加到购物车文本更改 - wordpress/woocommerce

Bru*_*dit 2 php wordpress woocommerce

我的 php 代码中出现致命错误,想知道如何修复它。

致命错误:PHP 致命错误: Uncaught Error: Call to a member function is_empty() on null in /home4/metis/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:7

代码:

add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );
function woocommerce_custom_add_to_cart_text( $add_to_cart_text, $product ) {
    // Get cart
    $cart = WC()->cart;
    
    // If cart is NOT empty
    if ( ! $cart->is_empty() ) {.  //line 7

        // Iterating though each cart items
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Get product id in cart
            $_product_id = $cart_item['product_id'];
     
            // Compare 
            if ( $product->get_id() == $_product_id ) {
                // Change text
                $add_to_cart_text = 'Already in cart';
                break;
            }
        }
    }

    return $add_to_cart_text;
}
Run Code Online (Sandbox Code Playgroud)

我想做的是,如果产品在购物车中,“添加到购物车”按钮文本应更改为“已在购物车中”。

小智 6

问题似乎是 $cart 为空,也许可以尝试:

if ( !is_null($cart) && !$cart->is_empty() ) {.  //line 7
Run Code Online (Sandbox Code Playgroud)

或者检查为什么 WC()->cart; 返回 NULL