skip to Main Content

I’m using this function to get the product name and return it in a short code:

public function getProducts() {
        $items =  $this->order->get_items();
        $product = chr(10);
        if(!empty($items)) {
            foreach ($items as $item) {
                $product_item = $item->get_product();
                if ($product_item) {
                    $product =  $item['name'];
                    
                }
            }
        }
        $return['{products}'] = $product;

in case of product with variations, I get:

parent name - variation name  (eg: shirt - black) 

but I’d like to get only the parent name.

How can I do to solve it?

2

Answers


  1. This should return the product name:

    $product_item->get_name();
    
    Login or Signup to reply.
  2. You should test if the product is a variation, and if so, get the parent product. Then you can get the name.

    if ($product_item->is_type('variable')) {
      $parent_product = wc_get_product($product_item->get_parent_id());
      $product = $parent_product->get_name();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search