Magento – Magento 2: Get Product via url with sku number in url

magento2.2.9product-urls

I have a magento 2.2.9 based site and wondering if its possible to get a product via url by having the sku in the url?

so something like https://www.domain.com/shop/?sku=123

Wanted to know if there is a default way to do this that wouldn't require building any custom module.

Best Answer

Try below code:

If Url like this https://www.domain.com/shop/?sku=123, then

Using Construct Method:

...
private $productRepository; 

protected $request;
...
public function __construct(
    ...
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Framework\App\Request\Http $request,
    ...
) {
    ...
    $this->productRepository = $productRepository;
    $this->request = $request;
    ...
}

public function loadMyProduct()
{
    $params = $this->request->getParams(); // all params
    if(is_array($params['sku']) && count($params) > 0){
        $proSku  = isset($params['sku']) ? $params['sku'] : '';
        $product = $this->productRepository->get($proSku);
        return $product;
    }
    return '';
}
...

Using Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$request       = $objectManager->get('Magento\Framework\App\Request\Http');
$params        = $request->getParams();
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$product = $productRepository->get($params['sku']);
echo "pro name".$product->getName()." == ".$product->getPrice();

Note: Magento did not recommend the Object Manager Method

I hope it will helps...!!!

Related Topic