web-dev-qa-db-ja.com

ウーコマースでのWC_Cartの拡張

私は自分のコードが正しいべきだと私が理解したものから、WC_Cartをwoocmerceで拡張しようとしています。ただし、カートをロードすると、次のようなメッセージが表示されます。

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

私のプラグインのコード:

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

出力コードは

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

これは/wp-content/plugins/woocommerce/classes/class-wc-cart.php内のコードが拡張しようとした瞬間に失敗したときに機能します。

2

WooCommerceカートクラスを拡張するのは少しトリッキーですが可能です。

拡張カートクラスを内部に含むプラグインとファイルclass-my-wc-cart.phpがあるとしましょう。それからメインのプラグインファイルで、あなたは以下をする必要があります:

// 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 );
        }
    }
}
4
Eugene Manuilov