title: Avoid error "call to a member function get_cart()…" in WooCommerce function
body: <p>Receiving an error on a code that did work previously but now it is stopping me editing a page in wordpress (As when I attempt to edit a page, it states there's been a critical error).</p>
  <p>The code below basically changes text for add to cart button depending if the related product is in the cart.</p>
  <p>Code below and error exception below that:</p>
  <pre><code>function woocommerce_custom_add_to_cart_text($add_to_cart_text, $product ) {
      global $woocommerce;
      // Get cart
      $cart_items = $woocommerce-&gt;cart-&gt;get_cart();
  
      foreach ( $cart_items as $cart_item_key =&gt; $cart_item ) {
          // Get product id in cart
          $_product_id = $cart_item['product_id'];
   
          if ( $product-&gt;get_id() == $_product_id ) {
              $add_to_cart_text = 'Already in cart';
          }
      }
  
      return $add_to_cart_text;
    
  }
  add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );
  </code></pre>
  <p>Error exception:</p>
  <pre><code>An error of type E_ERROR was caused in line 3 of the file /home4/metisonl/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code. Error message: Uncaught Error: Call to a member function get_cart() on null in /home4/metisonl/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:3
  Stack trace:
  #0 /home4/metisonl/public_html/staging/4326/wp-includes/class-wp-hook.php(287): woocommerce_custom_add_to_cart_text('Add to cart', Object(WC_Product_Simple))
  #1 /home4/metisonl/public_html/staging/4326/wp-includes/plugin.php(206): WP_Hook-&gt;apply_filters('Add to cart', Array)
  #2 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woocommerce/includes/class-wc-product-simple.php(62): apply_filters('woocommerce_pro...', 'Add to cart', Object(WC_Product_Simple))
  #3 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woo-gutenberg-products-block/src/BlockTypes/AbstractProductGrid.php(473): WC_Product_Simple-&gt;add_to_cart_text()
  #4 /home4/metisonl/public_html/staging/4326/wp-content/plugins/woo-gutenberg-products-block/src/BlockTypes/AbstractProductGrid.php(446): Automattic\WooCommerce\Blocks\BlockTypes\Abstra
  </code></pre>