I am trying to extend WC_Cart in woocommerce, from what i understand my code should be correct. However when I load the cart I get the following message.

Fatal error: Call to undefined method WC_Cart::get_prediscount_total() in ...

Code in my plugin:

class My_WC_Cart extends WC_Cart { 
    public function get_prediscount_total() {
        return apply_filters( 'woocommerce_cart_total', woocommerce_price( $this->total * 5 ) ); 
    } 
}

The output code is

 echo $woocommerce->cart->get_prediscount_total();

This works when the codes in /wp-content/plugins/woocommerce/classes/class-wc-cart.php but the moment I try to extend it it fails.

1 Answer
1

Extending WooCommerce cart class is a bit tricky, but possible.

Lets assume you have a plugin and a file class-my-wc-cart.php with extended cart class inside. Then in the main plugin file you need to do following:

// load your My_WC_Cart class
require_once 'class-my-wc-cart.php';

// setup woocommerce to use your cart class    
add_action( 'woocommerce_init', 'wpse8170_woocommerce_init' );
function wpse8170_woocommerce_init() {
    global $woocommerce;

    if ( !is_admin() || defined( 'DOING_AJAX' ) ) {
        $woocommerce->cart = new My_WC_Cart();
    }
}

// override empty cart function to use your cart class
if ( !function_exists( 'woocommerce_empty_cart' ) ) {
    function woocommerce_empty_cart() {
        global $woocommerce;

        if ( ! isset( $woocommerce->cart ) || $woocommerce->cart == '' ) {
            $woocommerce->cart = new My_WC_Cart();
            $woocommerce->cart->empty_cart( false );
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *