Include central function that applies for all my Wordpress themes
I have a Wordpress network with a big amount of different themes and even more pages using those themes.
Now, I have a PHP function (for some tracking) that I want to run every time a page from my network is accessed. I don't want to edit all my themes, so I am looking for a central file where I can have this new function.
First thing in my mind was the index.php in the root folder of the WP installation. This would probalby work but does not seem the finest solution.
All my themes are using the wp_head function maybe this can help somehow?
Is there any other place where I can add my tracking code and make sure that it is run on every page access?
Solutions
You should create a plugin to do this. In that plugin you will have that function and add the action to the wp_head hook . This will keep it working with all of your themes and easy to change without having to go into all your themes.
The code will look something like this
/**
* Plugin Name: Tracking Function
* Description: Lets me track my code
*/
function tracking_function(){
//enter code here
}
add_action("wp_head","tracking_function");
Then, because you have a network of sites, you will have to go into the Network Plugin manager, and activate the plugin for all networks and then you can activate or deactivate it for each specific site in your network.
The two options I can think of would be to use a plugin that loads "custom functions" for the sites that it is included on - much like
functions.php
in your theme, but independent of each theme. I wrote a plugin that does this which you can find here: http://justinsilver.com/technology/wordpress/wordpress-plugins/wordpress-plugin-custom-functions-php/
The other option would be to put a
PHP file
with your code into the
wp-content/mu-plugins
(Must-Use Plugins) that will be loaded before all other plugins on every site in your network. A bit more straightforward than the first option, but you can't selectively disable it should you
not
want on it on one of your network sites.