Extending WC_Cart in woocommerce

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 Comment