questions

Uncaught Error: Call to a member function is_empty() on null – add to cart text change – wordpress/woocommerce

Rate this post

I am getting a fatal error in my php code and want to know how to fix it.

Fatal Error: PHP Fatal error: 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

Code:

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;
}

What I am trying to do is if the product is in cart, the ‘add to cart’ button text should change to ‘Already in cart’.

 

✔️Solution:

The issue seems to be that $cart is null, maybe try:

if ( !is_null($cart) && !$cart->is_empty() ) {.  //line 7

Or check why WC()->cart; is returning NULL

Leave a Reply

Your email address will not be published.

Back to top button