1

How can I change the favicon of a Magento 2 store by code in my custom theme? without using admin backend interface.

1

Magento will get the default favicon from Magento_Theme module.

vendor/magento/module-theme/Model/Favicon/Favicon.php

 public function getDefaultFavicon()
 {
        return 'Magento_Theme::favicon.ico';
 }

So, in your custom theme, we can add favicon.ico:

app/design/frontend/Vendor/Theme/Magento_Theme/web/favicon.ico

If we want to know how Magento gets favicon in depth, we should take a look:

--vendor/magento/module-theme/Model/Favicon/Favicon.php

public function getFaviconFile() { ... }
public function getDefaultFavicon() { ... }
protected function prepareFaviconFile() { ... }

--vendor/magento/framework/View/Page/Config/Renderer.php

 public function prepareFavicon() { ... }
0

To override the default 16px x 16px favicon manually, add your custom favicon.ico in the /Magento_Theme/web/directory.

To add favicon icons of other sizes, take the following steps:

Add your icons in the /Magento_Theme/web/ directory. In the /Magento_Theme/layout/default_head_blocks.xml layout file specify the paths to the icons and their sizes.

For example, if you added a favicon-32x32.png icon and want it to be used as a 32px x 32px favicon, your default_head_blocks.xml would be like following:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Magento_Theme::favicon-32x32.png" rel="icon" sizes="32x32" />
    </head>
</page>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.