web-tip.top
WTT

Switch active theme depends on domain name

27.07.2024

On several projects I was needed to create 2 or 3 (sometimes 10) themes for website. This is usefull if you have main website and serveral child websites that use the same database. The easiest way is to swithc active theme depends on domain name requested.

Next code should be added to boot() method in Plugin.php of your plugin. First we check if domain was requested from frontend (in backend we can switch theme manually if needed) and return the code of desired theme. You need change domain1.com, domain2.com, theme-code-1, theme-code-2 and theme-code-3 to your values.


/*
 * Switch active theme depends on damin name requested
*/
if(!$this->app->runningInBackend()) {
   \Event::listen('cms.theme.getActiveTheme', function () {
       if (strpos(\Request::getHost(), 'domain1.com') === 0) {
           return 'theme-code-1';
       } elseif(strpos(\Request::getHost(), 'domain2.com') === 0) {
           return 'theme-code-2';
       } else {
           return 'theme-code-3';
       }
    });
}

Maybe this solution will not fit for complex websites but I didn't noticed any problems.