php - Magento 2 : How to get website Url by website Id in Observer

标签 php magento magento2

我的 magento 2 商店中有多个网站。 我正在创建自定义代码,因此我需要使用网站 ID 访问网站 Url,我尝试了很多不同的方式,但我无法获取 url。

$this->_objectManager->getWebsite(1)->getDefaultStore()->getBaseUrl();

我也在尝试另一种方式是:

 public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Linksture\ApplyCoupon\Model\ApplyCouponFactory $applycouponFactory,
    \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collectionFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory $couponcollectionFactory
    ) {
$this->_scopeConfig = $scopeConfig;
$this->_applycouponFactory = $applycouponFactory;
$this->_collectionFactory = $collectionFactory;
$this->_storeManager = $storeManager;
$this->_couponcollectionFactory = $couponcollectionFactory;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{  
    echo $this->_storeManager->getWebsite(1)->getDefaultStore()->getBaseUrl();
}

在 magento 1.x 中,使用如下。

Mage::app()->getWebsite(1)->getDefaultStore()->getBaseUrl();

最佳答案

假设你有多个网站,一个网站在多个商店下,你得到所有的baseUrlwebsiteIdstoreId

 public function __construct(
            \Magento\Framework\ObjectManagerInterface $objectManager    
        ) {
            $this->_objectManager = $objectManager;
        }

        public function execute(\Magento\Framework\Event\Observer $observer){
            $storeManager =  $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
            $websites = $storeManager->getWebsites();
            foreach($websites as $website){
                foreach($website->getStores() as $store){
                    $wedsiteId = $website->getId();
                    $storeObj = $storeManager->getStore($store);
                    $storeId = $storeObj->getId();
                    $url = $storeObj->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
                }
            }

        }   

关于php - Magento 2 : How to get website Url by website Id in Observer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563076/

相关文章:

php - Codeigniter分页概念问题

javascript - 怎么调404页面去搜索

knockout.js - Knockoutjs - 我可以将数据绑定(bind)属性与 i18n 一起使用吗?

php - Magento 2 Apache 随机 400 错误

php - Hash Secure 不适用于 MIGS 支付

Git - 在 magento 中找不到匹配版本的包

javascript - 检查前端和后端

php - 从数据库中清除过期 session

php - 数学统计,如何计算预测

php - 优化数据库查询 MySQL 和 PHP