Magento 2 redirect to a specific store view programatically

Use StoreManagerInterface to set current store. You can use observer to do so.

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $_storeManagerInterface;


//Inject your class
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
) {
    $this->_storeManagerInterface = $storeManagerInterface;
}

// Use It in your method
public function execute(){
    $this->_storeManagerInterface->setCurrentStore(1);
}
///////////////////////////////////////////////////////////////////////////

$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeCookieManager = $objectManager->create('\Magento\Store\Api\StoreCookieManagerInterface');
$httpContext = $objectManager->create('\Magento\Framework\App\Http\Context');

$defaultStoreView = $storeManager->getDefaultStoreView();
$httpContext->setValue(\Magento\Store\Model\Store::ENTITY, $store->getCode(), $defaultStoreView->getCode());
$storeCookieManager->setStoreCookie($store);

Leave a comment

Your email address will not be published. Required fields are marked *