Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento2 如何获取基本URL

在magento 2。

如果要获取基本url,则可以尝试以下代码:

/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/

$this->_storeManager->getStore()->getBaseUrl();

$this->_storeManager实例\Magento\Store\Model\StoreManagerInterface

上面的代码将为您提供结果

https://www.sbboke.com(如果启用了Seo重写

和 https://www.sbboke.com/index.php(如果未启用Seo重写

如果您希望基本网址不包含 index.php

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB)

使用对象管理器

基本网址:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeManager->getStore()->getBaseUrl();

没有index.php的基本网址

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

要获取媒体基本网址:

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

获取链接网址:

$this->_storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

编辑

为了获得 $this->_storeManager 您应该依赖注入\Magento\Store\Model\StoreManagerInterface $storeManager

在 __construct( )功能块类

就像 :

public $_storeManager;
  public function __construct(
      \Magento\Store\Model\StoreManagerInterface $storeManager,
       .....
    ) {
       ...
  $this->_storeManager=$storeManager;
    }

更新:

此外,您还可以得到基本的URL 直接phtml使用的直接调用object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

注: Directly call of object manager is not good idea。如果您想要在phtml的基本网址,则StoreManagerInterface在块插入

版权属于: sbboke版权所有。

转载时必须以链接形式注明作者和原始出处及本声明。

张贴在magento2教程标签:

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论