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
The issue seems to be that $cart is null, maybe try:
Or check why WC()->cart; is returning NULL
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: