0

I have a problem with calling a class method from inside a wp_ajax_function. My code looks like this:

 class Cart {

    public $cart_content;
    public $cart_id;
    public $db;

    public function __construct() {
        $this->db           = $GLOBALS['wpdb'];

        add_action( 'wp_ajax_update_cart', array($this, 'update_cart') );
        add_action( 'wp_ajax_nopriv_update_cart', array($this, 'update_cart') );
    }

    public function get_cart_content($cart_id = false) {
        if( !$cart_id ) $cart_id = $this->cart_id;

        $content = $this->db->get_row( $this->db->prepare("SELECT content FROM {$this->db->prefix}$this->cart_table WHERE cart_id = '%s'", $cart_id) );
        $this->cart_content = $content ? unserialize($content->content) : $content;

        return $this->cart_content;
    }

    public function update_cart() {
        $items = $_POST['items'];

        wp_send_json( $this->get_cart_content()) );
    }

The problem is that I cannot access class properties inside updat_cart() function. So when I call get_cart_contents() method it return null. Thanks in advance for any help. Rafal

2
  • Never mind. SOLVED
    – Raf
    Commented Apr 18, 2017 at 13:18
  • Glad you solved it, but please add your solution as an answer (then stop by in a couple of days and click the checkmark to accept it) so that this post will potentially be helpful to someone in the future. Commented Apr 18, 2017 at 13:24

1 Answer 1

0

The problem was caused by another method inside the class:

     public function create_cart_id() {
        if( is_user_logged_in() ) {
            $this->create_logged_in_cart_id();
        }else {
            $this->create_non_logged_in_cart_id();
        }

        return $this->cart_id; - adding that line solved the problem
    }

This method generates the $cart_id, but it didn't return its value, so it was not accessible from outside and returned null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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