How to get the Magento 2 Base URL

0

When programming in Magento 2, we at Codingbasics.net often come across the issue of getting the base url of the current store. This was very easy to do in Magento 1, but in the second version of the shopping cart CMS it’s done a bit differently. In this post, we will show you how to do this.

To get the base URL in Magento 2 use the following code.

You can also use the following code which gives you the store id as well.

To get the Media base URL use the following.

And last but not least, to get the link URL use this.

Although it’s not recommended, you can also get the base URL directly in phtml by using the direct call of object manager. This can be done with the following code snippet.

This is, however, a very resource intensive task that isn’t very efficient. Use this only if no other method works, or if the piece of code is rarely used in your Magento 2 store. If you have more questions or problems, leave a comment in the comment section below and we’ll answer and help you.

Share.

Leave A Reply