Using conditional file loading in WordPress plugins

Faster loading WordPress installations is our goal, by making our plugins just a little bit smarter. Basic rule is: when we don’t need a file, don’t include it! When you write a plugin for the Dashboard, it is of no use loading the files used by the plugin at your homepage or at a single posts page. For example:

[sourcecode language=”php”]if(is_admin()) {
include("admin_plugin.php");
}[/sourcecode]

The imaginary plugin that we’re writing here, has some functionality in the WordPress Dashboard. We split up that functionality in a file called plugin_admin.php and we only include it inside the Dashboard. Whenever we are on a page outside of the Dashboard, the file will not be included, which will result in a faster loading page.

Using other WordPress conditions

Besides is_admin(), we have a few common conditions inside WordPress. With is_single() we check if the current page is a single post page and with is_category() we check for a category page. It would be cool if we could use these conditions inside our plugins to determine wether or not a file is needed.

But there is the catch. Conditions like is_single() and is_category() do not work inside a plugin because WordPress loads the plugins way before it knows what kind of page it is at. A great workaround is to hook your script to the wp-hook, so it will be executed right after the posts are loaded, so WordPress knows the type of the page.

A quick example to get you going. In this script, a function is added to the wp-hook, that will include a plugin file, only when we’re at a single post page:

[sourcecode language=”php”]add_action("wp", "load_plugin");
function load_plugin() {
if(is_single()) {
include("single_plugin.php");
}
}[/sourcecode]

Using a load-function inside the wp-hook, we can use conditions like is_single() just like is_admin() inside a plugin. This way you can start preventing your plugins from loading files that WordPress does not need at certain pages.

You might need to restructure your plugin a bit to make it work this way. But when used effectively, it will make all WordPress installations a lot faster.