Support » Plugin: WooCommerce » Uncaught Error for get_cart() function?

  • Resolved AJD

    (@ajd)


    I am getting the following error and the the WordPress menus in Settings -> Menus are broken. (Fresh WP install, latest version of Woocommerce, default theme, except for one code snippet in function.php below)

    PHP Fatal error: Uncaught Error: Call to a member function get_cart() on null in /home/public_html/devwoo/wp-content/themes/twentynineteen/functions.php:336
    #6 /home/public_html/devwoo/wp-admin/nav-menus.php(849): do_accordion_secti in /home/public_html/devwoo/wp-content/themes/twentynineteen/functions.php on line 336

    Here is the code I have added:

    add_filter( 'woocommerce_available_payment_gateways', 'filter_gateways', 1);
    function filter_gateways( $gateways ){
    
        // storing special product IDs in an array
        $non_pp_products = array( 10);
    
        // Needed variables
        $is_non_prod = false;
        $is_prod = false;
        $count = 0;
    
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // count number of items if needed (optional) 
            $count++;
            $product = $cart_item['data'];
            if( ! empty($product) ){
                $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
                if ( in_array( $product_id, $non_pp_products ) && ! $is_non_prod ) 
                    $is_non_prod = true;
    
                if ( !in_array( $product_id, $non_pp_products ) && !$is_prod )
                    $is_prod = true;
    
            }
        }
        if ( $is_non_prod && ! $is_prod ) // only special products 
        {
            // unset only paypal;
            unset( $gateways['paypal'] );
        } 
        elseif ( $is_non_prod && $is_prod ) // special and normal products mixed
        {
            // unset ALL GATEWAYS
            unset( $gateways['cod'] );
        }
        elseif ( ! $is_non_prod && $is_prod ) // only normal products (optional)
        {
            // (unset something if needed)
        }
        return $gateways; 
    }
    
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Uncaught Error for get_cart() function?’ is closed to new replies.