magento2 get base url and media url and static url

magento2 get base url and media url and static url

If you use magento2, then you must need magento2 get base url and media url and static url for your current store.

In here, i am tried to give you to get base ,media ,static urls in magento
At phtml file you need to use below code:

In block class, you can use below codes:

Else you can try below solution which is better than above you can use this code at Block/helper/controller/Model at anywhere.

Use below for getting base URL

 

Use this as an alternative

For getting media url:

For getting link url:

For getting static url:

For getting static Js Url:

Most important thing:
In several cases, you need to current store base url.at Magento 1.x version you can get base url using Mage::getBaseUrl();

As Magento2, not used factory patterns, so there have no code like Mage::getBaseUrl(); by which you can base URL.But at Magento2, you should use StoreManager object then using $this->_storeManager->getStore()->getBaseUrl() you can get base url.

Magento2, use interface, injection of class, that you should Inject

at Model, Resource model, Helper classes for getting base url.

In below example class, I have injected StoreManagerInterface my class

 

 

Note that: if you have used any block class which extends base block template

and should avoid injected of store manager interface for that case as extends class already have store Manager object

try below code to get magento2 base URL:

 

 

How to get magento2 base url by Object Manager

Using Object manager for getting magento2 base URL then try below once:

Assume that your class has object manager.

If don’t have object manager then try this:

But this type of object manager calls is really bad idea.
Related Post:

  1. How to get magento2 base url
  2. Magento2 redirection from Observer

 

3 thoughts on “magento2 get base url and media url and static url

Leave a Reply

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