thefonz
thefonz

Reputation: 96

Storing WP Variable from cart meta (Woocommerce)

I am having some issues trying to retrieve and store a variable from the cart meta - The loop is working fine using the code below:

if (WC()->cart) {

         foreach (WC()->cart->get_cart() as $item) {
           $product = $item['data'];
           $prod_id = wdcp_get_product_id_cart_item($item);
           echo $product;
         }
    }

Result:

{"id":26036,"key":"_credits_amount","value":"15"}

I would like to take this value (_credits_amount) and store it in a variable but cant figure out how to pinpont locate it via the code... any help would be much appreciated?

Upvotes: 0

Views: 65

Answers (2)

Ivnhal
Ivnhal

Reputation: 1095

You need to decode JSON:

foreach (WC()->cart->get_cart() as $item) {
    $product = $item['data'];
    $prod_id = wdcp_get_product_id_cart_item($item);
    $data = json_decode( $product, true);
    echo $data['value'];
}

Upvotes: 1

kashalo
kashalo

Reputation: 3562

this data are object of type WC_Product_Simple so id you want to get the _credits_amount and store it in variable you can do so as follow:

$key = $product->key;

full code :

if (WC()->cart) {

    foreach (WC()->cart->get_cart() as $item) {

    $product = $item['data'];
    $key = $product->key;

    echo $key;

  }
}

Upvotes: 1

Related Questions