Plugin Dev 101- Prefix your Functions

It’s been almost 2 years now since I entered the world of WordPress plugin development. It’s been a huge (but very rewarding) learning curve. I’d like to share a few basic “plugin dev 101” tips here. I know my observations on these topics probably won’t be unique, but hopefully this series of nice simple tutorials will be useful to someone.

Lesson 1 – Prefix your Functions

It’s important to use unique and descriptive names for the functions in your plugin.  I’ve been caught out a few times using function names that were far too generic. This resulted in conflict with other plugin/s using the same name, usually triggering this error message:  “Fatal error: Cannot redeclare [my generic name] function”

Luckily it’s simple to avoid this boo boo by using a unique prefix for functions like this example:

myplugin_function1 () {
	// do stuff
}

myplugin_function2 () {
	// do more stuff
}

Another somewhat superior option is to define your plugin functions inside a class (also with a unique name), something like this:

class my_unique_plugin_class {

	function1 () {
		// do stuff
	}

	function2 () {
		// do more stuff
	}
}

As you can see, using a class is a nifty way to avoid the conflict. There’s a great article by Tom McFarlin here if you want to explore this idea further. Andrew Nacin also has an excellent post discussing the issue of prefixing in WordPress here.

Ultimately one of the biggest challenges as a plugin developer is to ensure your plugin works side by side with other plugins. Avoiding generic names for functions may seem obvious, but I’d bet my best hat I’m not the only plugin developer to have been caught out on this one!

Thanks and feel free to comment or share 🙂

Leave a Comment

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