Shared functions.php across WordPress multi-sites

Advertisement:

Ever wondered how you could use a shared functions.php in a WordPress multisite (WPMU) environment? If you are using a WordPress multisite setup you’ve probably come across using the same custom WordPress functions over and over again. As a theme developer, you might already have created a functions.php blueprint that you will use in every new theme. In this article, I will show you how to set up and implement a shared functions.php that you are be able to use across a WordPress multisite installation. It would also work if you are using seperate signle WordPress installations on one host.

The example case

For the different multi-site setups in my projects, there is one code snippet, that is repeatedly being used. If you are maintaining a WP multisite with different themes for each site, you’ll probably have a similar code snippet: the Google Analytics tracking code. So for this article, I will walk you through with the basic example of implementing the Google Analytics tracking code in a shared functions.php.

Create the file and folder for your shared functions.php

I chose to name my folder commons and created it in the themes-folder. So the first two steps to your shared functions.php in WordPress multisite are:

  1. Create the folder wp-content/themes/commons/,
  2. Create the file functions.php within this folder.

Add some useful code to your shared file

As said, as example I will help you to implement a basic version of the Google Analytics tracking code. This code will be re-usable throughout each theme in your WordPress multisite setup. But there’s one major thing you’ll have to consider: Each site you would want to track is a seperate property and has its own tracking ID. So I will alter the default Google Analytics tracking code to respect that fact. Instead of using a hard coded Google Analytics tracking ID, you will use a PHP variable instead.

After creating the folder and files, add this code to your /commons/functions.php to use the tracking code through your shared functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Common functions extending each WP's header.
 * E.g. Google Analytics Tracking code
 */
 
if ( ! function_exists( 'add_google_analytics' ) ) :
 
function add_google_analytics($analytics_id) { ?>
 
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', '', {'siteSpeedSampleRate':50});
  ga('require', 'linkid', 'linkid.js');
  ga('set', 'forceSSL', true);
  ga('set', 'anonymizeIp', true);
  ga('send', 'pageview');
<?php
}
 
endif; // function_exists 'add_google_analytics'

As an advanced WordPress developer, you know the benefits of capsulating functions in an if (! functions_exists( 'function_name' ) ):-clause. By using these two little lines as wrapper, you can always override the named function in a template file. Make sure not to forget the endif;.

Include the shared functions.php in your theme

This turned out to be a tricky part. Until using a shared PHP-script, I was including JavaScript- and CSS-files from the commons-folder using WordPress’ native get_theme_root_uri() function, adding the appropriate subfolder(s) to the file-strings.

But in this case, we are about to include PHP code from an “external” file. This lead me in using the require_once statement. But with including a PHP-file, you cannot use the get_theme_root_uri() function anymore. It will – as its name implactes – return a URI with http:// in the beginning. Unfortunately, this is a not allowed by default settings in the php.ini.

To include the shared functions.php into your local theme’s functions file, we’ll use a an absolute path instead. The PHP variable $_SERVER['DOCUMENT_ROOT'] suits best four our case. Be aware, that when you installed WordPress into a subfolder, you will have to add this subfolder, too. The line of PHP you’ll add to your local functions.php therefore is:

require_once($_SERVER['DOCUMENT_ROOT'].'/[your-wp-subfolder]/wp-content/themes/commons/functions.php');

Make use of the shared functions.php in you theme

After you included (or actually: required) the shared functions PHP-script to load, you are able to use its functions just as if they were inside your local theme’s functions file.

To add the Google Analytics Tracking code to you site, you’d simply call the add_google_analytics()-function. But we were using a variable there, remeber? To add the correct tracking-ID to the JavaScript-code that the function returns, just add this ID between the brackets as string: add_google_analytics('UA-00000000-1');.

You could assign the tracking-ID as variable and pass this to the function. So your function-call for Google Analytics tracking would be something like

function load_analytics() {
	$analytics_id = 'UA-00000000-1';
	if ( !is_user_logged_in() ) { add_google_analytics($analytics_id); };
}
add_action( 'wp_head', 'load_analytics' );

This function will load the Google Analytics script inside the header of your WordPress theme. But before executing the functions to add the script, it will check if the current viewer is logged in. I use this conditinonal to make sure that my own hits on the sites are not being tracked while I am writing posts and checking their previews.

Summary

When you have a WordPress multi-site setup, or are maintaining multiple WordPress single installations on the same server, you will come to use the same function declarations in each theme’s functions.php. By using a shared functions.php you can clean up the PHP-code of your single themes or child themes. When creating new themes, you will already have a useful stack of already developed functions. This is possible as long as your shared functions file is accessible from the same server. A shared functions.php will help you to be a more efficient WordPress developer.

If you have suggestions, want to share improvements or new ideas, or found a bug consider leaving a comment :-)

Useful links

  1. Set up Google Analytics Tracking
  2. Function Reference for get_theme_root_uri() from the WordPress Codex
  3. Action reference for the wp_head from the WordPress codex.
  4. PHP’s $_SERVER variables explained in the official PHP documentation.
  5. PHP’s require_once explained in the official PHP documentation.
  6. Not sure which statement to use for including a PHP file? See this stackoverflow answer: require vs. include explained.
Like this post? Share it!
Advertisement:

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>