skip to Main Content

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’.

2

Answers


  1. 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

    Login or Signup to reply.
  2. You’re doing it right, it should work, the only thing i can think of is that you’re hooking it too early where WC()->cart is not defined, maybe you can wrap the code in a later hook:

    add_action('wp', function() {
        add_filter( 'woocommerce_product_add_to_cart_text', function($add_to_cart_text, $product) {
            if (WC()->cart->is_empty()) {
                // Do your thing
            }
        }, 10, 2 );
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search