Question

I have this script working on Magento 1.9 but can't figure out how to use it for Magento 2.2.7.

<?php
require_once 'app/Mage.php';
$sku = $_GET['sku'];
$store = Mage::app()->getStore();
$path = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku)->getUrlPath();
$url = $store->getBaseUrl($store::URL_TYPE_WEB);
header("HTTP/1.1 301 Moved Permanently");
$headerURL = "Location: " . $url . $path;
header($headerURL);
exit();
?>
Was it helpful?

Solution

Try below code

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
/*---------------------------------------------------------------------------*/

$sku = $_GET['sku'];

$product = $obj->create('\Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);
if(is_object($product)){
    header("HTTP/1.1 301 Moved Permanently");
    $headerURL = "Location: " . $product->getProductUrl();
    header($headerURL);
    exit();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top