In the last post we learned the basics for creating our very own WordPress plugin. Now I would like to show you how to make them really do something. What I mean by that is that our last post really only created the container. In order for the plugin to be really useful we need to, at the very least…
- Add some code
- Tell that code when to run
This is perhaps a little of an oversimplification. Certainly you might want to add options and many other things but what we’ll share here will get you well on your way to doing all of that. Let’s get familiar with the most useful tool in plugin development.
Hooks
Hooks are basically functions or pieces of code that run at specific times when a WordPress page loads. Think of them like placeholders that you can assign your super fabulous pieces of code too. WordPress has these hooks all throughout it’s code and they are really the secret as to why WordPress is so easy to extend. Becoming familiar with these hooks and when they run can be invaluable to your next project.
There are to types of hooks that you can use.
- Action Hooks – These are those placeholders we referred to earlier. When a page loads and it comes to one of these hooks it will process whatever code you attached to them. There are actions for almost everything that happens within WordPress. When you change themes, publish a post, or when admin menus are run. Learn more about Actions here. For a list of available Actions within WordPress check out the Codex.
- Filter Hooks – These are very similar to “Action Hooks” except that they usually come with content already associated with them. When attaching your code to a Filter you are going to actually alter that content. You might change something about the content, append your own data before or after the content, or remove the content altogether. Learn more about Filters here. For a list of available Filters within WordPress check out the Codex.
Perhaps in a future post I’ll dig into each of these in greater detail but for now this gives us a good understanding to move forward. So let’s create a plugin that solves a real problem you may have faced before.
A Real World Example: Google Analytics
Perhaps you have had this happen to you. It used to happen to me all the time when I first got started using WordPress for my personal site. We all want to track how our website is doing so we get our Google Analytics code and place it right where Google tells us to, right before the closing </head> tag. With most WordPress theme this is usually in the header.php file. Or you followed a tutorial like the one from WPMU.org. I’m sure the author meant well but it creates a problem.
Things are going great and the data is coming in just fine. One day you decide that your bored with your current theme and you decide to switch to a new one. It’s always nice to had a fresh coat of paint. A couple weeks later you are checking your Google Analytics stats only to discover that data has ceased being collected. What happened?
If you read some of our previous posts you know exactly what happened. So you copy the code from your old theme and place it into the new one only to have the same thing happen the next time you switch you theme. These simple steps will fix that once and for all.
Step 1: Create your plugin files
Just follow along from our post on How to Create a WordPress Plugin. Don’t activate it just yet.
Step 2: Create a function in that file that outputs your Google Analytics code.
[php]
function wpnj_add_analytics() {
$analytics = “<script type=’text/javascript’>
var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-999999-99’]); // Replace this with your own Anayltics Code
_gaq.push([‘_trackPageview’]);
(function() {
var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
})();
</script>”;
echo $analytics;
}
[/php]
Be sure to replace UA-999999-99 with your own actual Google Analytics ID.
Step 3: Attach your new function to the correct action.
In this situation we want our analytics code to be output right before the closing </head> tag. The best action that all themes should be implementing is the wp_head action hook. We’ll attach it to that. It would look like this…
[php]
add_action( ‘wp_head’, ‘wpnj_add_analytics’ );
[/php]
Here is what the plugin would look like altogether.
[php]
<?php
/*
* Plugin Name: My Google Analytics
* Description: This plugin outputs my Google Analytics code.
*/
add_action( ‘wp_head’, ‘wpnj_add_analytics’ );
function wpnj_add_analytics() {
$analytics = “<script type=’text/javascript’>
var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-999999-99’]); // Replace this with your own Anayltics Code
_gaq.push([‘_trackPageview’]);
(function() {
var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
})();
</script>”;
echo $analytics;
}
[/php]
Step 4: Upload and Activate your plugin.
That’s it. You have just created an extremely useful plugin for your WordPress website. Now the next time you want to switch themes you can be confident that Google Analytics will continue to capture that valuable visitor data. Don’t forget to remove the analytics code from your header.php now. 🙂
This is just a quick example of the usefulness of WordPress plugins and the power of hooks. Certainly much more can be done depending on your imagination and skill level.
Preventing Conflicts
One thing to watch out for if you create a few plugins and also install several others is the possibility of conflicts. For instance, you can’t have the same function name declared twice. Say in our example above I had named my function google_analytics and then installed another plugin that had a function with the same name. Needless to say errors would occur and we don’t want that. This is where a concept called “prefixing” comes in to play.
Simply add a personal identifier to every function name you create. In our example, instead of just using google_anaytics I named the function wpnj_google_analytics. I use either wpnj for wpninjas or ninja as a prefix for all my functions to lessen the chance of conflicts with someone else’s code. You can use your initials or whatever. Just pick something and be consistent. It will make your life a lot easier.
I hope you found this little tutorial helpful.
Joshua says
Awesome article James! Thank you for this. I just opensourced a CMS and am looking to implement a plugin system, and this is just the kind of article I was looking for… I look forward to read more of your work,!
Hany Adel says
Great article, thanks
Martin Pfeffer says
Good work! Thank you, James.