You can check if a product has a custom option exists (hasOptions()) or not in Magento 2 by Product Object.
Some product type contains options like Bundle and Configurable while Simple, Virtual, Grouped, Downloadable and gift card doesn’t support options.
You can check product has options by loading Product object with $product->hasOptions() function.
<?php namespace Jesadiya\HasOptions\Model; use Exception; use Psr\Log\LoggerInterface; use Magento\Catalog\Api\ProductRepositoryInterface; class ProductOptions { /** * @var LoggerInterface */ private $logger; /** * @var ProductRepositoryInterface */ private $productRepository; public function __construct( LoggerInterface $logger, ProductRepositoryInterface $productRepository ) { $this->logger = $logger; $this->productRepository = $productRepository; /** * @var ProductRepositoryInterface */ private $productRepository; } /** * result * * @return bool */ public function hasOptionsProduct() { $sku = '24-WG080'; $hasOptions = false; try { $product = $this->productRepository->get($sku); $hasOptions = $product->hasOptions(); } catch (Exception $exception) { throw new Exception($exception->getMessage()); } return $hasOptions; } }
Call from the template or any PHP class,
echo $productHasOptions = $this->hasOptionsProduct();
Sample data with different type of products,
’24-WG080′ = Bundle (HasOptions 1)
‘MJ08’ = Configurable (HasOptions 1)
’24-WG085_Group’ = Grouped (HasOptions 0)
‘240-LV04’ = Downloadable (HasOptions 0)
’24-MB01′ = Simple (HasOptions 0)
Virtual product (HasOptions 0)
Output:
boolean