Freedom, Community & Sustainability

Identify a drupal 7 multisite in code (without using the URL)

December 8, 2014 -- William
Last modified on November 2016
Duration: 5 minutes or less

When working with themes in drupal multisites you might want to display certain things only on one multisite using the theme preprocess functions and outputting them on a .tpl.php file.

You might notice that none of the variables available refer to the multisite you are working with. One workaround would be to use the URL through the $_SERVER variable in order to identify the site that is active. This is a bad solution because URLs might change (and they do change between development and production environments, making the workaround become a fragile and overly complicated code).

To deal with this you only need one simple function: conf_path()that returns the path to the configuration file settings.php. Since there must be a settings file for each multisite and they are placed on the folder of the multisite, you can be sure to get a unique string that is unlikely to change for each multisite. Then you can use either the entire string returned by the function or break it down to have only the folder of your multisite and store it in a variable.

In the template.php file enter the following code into your preprocess function:

$multisite = array_pop(explode('/', conf_path()));

The conf_path() function will return the path to the settings.php file starting from drupal root. Then we divide the string into an array with the explode() function that splits the string on '/'. Finally we get the last element of this array with array_pop() in order to get the folder name of the multisite and assign it to the $multisite variable.

Now you can create the logic of your template.php file using something like a switch statement and doing different things on different multisites.

switch($multisite) {
    case 'example.com':
        $variables['mystring'] = "This is the example.com site!";
    case 'example.net':
        $variables['mystring'] = "This is the example.net site!";
        $variables['mystring'] = "This is the default site!";

After doing that you can place the variable $mystring in your page.tpl.php file and it will print the correct sentence for each multisite.

If you are not familiar with drupal theming and some of the above code is confusing, take a look at the drupal documentation themer guide.

Add new comment