2

I'm trying to get the SKU of all the products in my cart. In the past i tried something similar with the product names. I did it like this:

global $woocommerce;
$items = $woocommerce->cart->get_cart();
$product_names=array();
foreach($items as $item => $values) { 
    $_product = $values['data']->post; 
    $product_names[]=$_product->post_title; 
} 

Is there a way like this but instead of the title get the SKU of a product?

EDIT:

I tried Thoby's way like this :

global $woocommerce;
$items = $woocommerce->cart->get_cart();
$product_names=array();
$productsku=array();
foreach($items as $item => $values) { 
    $_product = $values['data']->post; 
    $product_names[]=$_product->post_title;
    $productsku[]=  $_woo_product->get_sku();
} 

But i get an error :

Fatal error: Call to undefined method WP_Post::get_sku()

1
  • 1
    The product object should have an sku property. Have you tried returning the $_product object and seeing what properties it has?
    – mikeg542
    Apr 19, 2017 at 13:42

4 Answers 4

4

Try :

global $woocommerce;
$items = $woocommerce->cart->get_cart();
$product_names = array();

foreach($items as $item => $values) { 

    // Retrieve WC_Product object from the product-id:
    $_woo_product = wc_get_product( $values['product_id'] );

    // Get SKU from the WC_Product object:
    $product_names[] = $_woo_product->get_sku(); 
}

The official WooCommerce API docs: wc_get_product()

1
  • You didn't seem to have copied the content of my code. I use the function wc_get_product, which would return a WC_Product object instead of a WC_Post.
    – Thoby
    Apr 19, 2017 at 14:00
4

I believe this might help you-

$_product->get_sku();

It works with product loops and you can use it inside your cart/checkout/etc..

0
2

I assume you already have access to $cart

$cart_items = $cart->get_cart_contents();
$skus = array(); 

foreach($cart_items as $cart_item) {     

 // Get WC_Product by Variation ID, if not avaiable use Product ID
 $product = wc_get_product($cart_item["variation_id"] ? $cart_item["variation_id"] : 
 $cart_item["product_id"]);

 // Add new SKU to array
 array_push($skus, $product->get_sku());     
}
1

The easiest way to get the SKU of a product when you have access to the cart items:

$cart = WC()->cart->get_cart();
  
foreach( $cart as $cart_item_key => $cart_item ){

    $product = $cart_item['data'];

    $product->get_sku();

}

Your Answer

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

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