0

I have a class that I want to use in functions.php but I'm not sure the best way to set it up

I also want to get WooCommerce's cart array. I currently do not have access to WC() in my class yet.

What is the best route to achieve OOP in functions.php and whats the best way to get WooCommerce's class WC() to my class so I can use for other functions.

my code in functions.php

class MyCart {
    public $cart_contents;

    public function __construct(){
        add_action( 'get_header', [ $this, 'set_users_cart_contents' ] );
        //$this->set_users_cart_contents();
    }

    public function set_users_cart_contents() {
        $this->cart_contents = WC()->cart->get_cart_contents(); // what i want to use
        //$this->cart_contents = ['test' => '123']; // dummy array for testing
    }

    public function get_users_cart_contents() {
        return $this->cart_contents;
    }
} // class

$cartClass = new MyCart();

// add action
function emdr_add_to_cart(){
    // I want to use my class here
    // $items = $cartClass->get_users_cart_contents();
}
add_action( 'woocommerce_add_to_cart', 'emdr_add_to_cart');

// add action
function cart_page_logic(){
    if(is_cart()){
        // I want to use my class here
        // $items = $cartClass->get_users_cart_contents();
    }
}
add_action( 'get_header', 'cart_page_logic' );
0

If you have defined the class MyCart directly in functions.php with your hooks. I'd expect for the following to work:

// add action
$cart = new MyCart();
function emdr_add_to_cart(){
    $items = $cartClass->get_users_cart_contents();
    // process items
}
add_action( 'woocommerce_add_to_cart', 'emdr_add_to_cart');

I might also add that duplicating the "state" of the users cart in 2 places is probably a code smell. I would suggest using the values directly from the WooCommerce cart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.