phpwordpress

Get slug from a woocommerce product using a product id


I want to get the slug of each product in a woocommerce order/purchase of current user.

Steps i took

1.I fetched current user's order.

2.Then I get items/products from the order

$args = array(
    'customer_id' => $user->ID
    'status' => 'completed'
);
//getting the orders 
$orders = wc_get_orders($args);
$orderInfo = [
'id' => [],
'name' => [],
'slug' => []
];
foreach($orders as $order){
  foreach( $order->get_items() as $item_id => $item ){
    array_push( $orderInfo['id'], $item->get_product_id() );
    array_push( $orderInfo['name'], $item->get_name() );
    array_push( $orderInfo['slug'], $item->get_slug() );
  }
}

After fetching products i am able to get product id and name. But when using $item->get_slug, I am facing this error.

Fatal error: Uncaught Error: Call to undefined method WC_Order_Item_Product::get_slug()

What wrong am i doing?


Solution

  • You should try this

    $product = get_post( $item->get_product_id() );
    $slug = $product->post_name;
    array_push( $orderInfo['slug'], $slug );