WC_Order_Item_Product::get_product PHP Method

get_product() public method

Get the associated product.
public get_product ( ) : WC_Product | boolean
return WC_Product | boolean
    public function get_product()
    {
        if ($this->get_variation_id()) {
            $product = wc_get_product($this->get_variation_id());
        } else {
            $product = wc_get_product($this->get_product_id());
        }
        // Backwards compatible filter from WC_Order::get_product_from_item()
        if (has_filter('woocommerce_get_product_from_item')) {
            $product = apply_filters('woocommerce_get_product_from_item', $product, $this, wc_get_order($this->get_order_id()));
        }
        return apply_filters('woocommerce_order_item_product', $product, $this);
    }

Usage Example

 /**
  * Create or update a line item.
  *
  * @param array $posted Line item data.
  * @param string $action 'create' to add line item or 'update' to update it.
  * @throws WC_REST_Exception Invalid data, server error.
  */
 protected function prepare_line_items($posted, $action = 'create')
 {
     $item = new WC_Order_Item_Product(!empty($posted['id']) ? $posted['id'] : '');
     $product = wc_get_product($this->get_product_id($posted));
     if ($product !== $item->get_product()) {
         $item->set_product($product);
         if ('create' === $action) {
             $total = $product->get_price() * (isset($posted['quantity']) ? $posted['quantity'] : 1);
             $item->set_total($total);
             $item->set_subtotal($total);
         }
     }
     $this->maybe_set_item_props($item, array('name', 'quantity', 'total', 'subtotal', 'tax_class'), $posted);
     return $item;
 }