When it comes to plugin development – be it either widgets or plugins – there are several different ways in which we can instantiate a WordPress plugin.
Unfortunately, you’re likely to get a different answer depending on who you ask, or what you read.
Case in point: According to the WordPress Codex, instantiating a WordPress widget is done like this:
add_action( 'widgets_init', create_function( '', 'register_widget( "foo_widget" );' ) );
But I know several people who are adamantly against using create_function
.
Though I personally don’t have a problem with it, I’m always interested in hearing others’ approach to how they do it and why.
So in this post, I thought I’d lay out the various ways to instantiate a WordPress plugin, pros and cons of each, but also ask each of you what your favorite method is and why.
Instantiate a WordPress Plugin
Since WordPress plugins can be divided into plugins or widgets, I’m laying out each one individually as well as the problems that I’m aware of for each of the approaches.
Note that each of the following examples is based on object-oriented programming techniques. If you’re using hooks and functions, then this doesn’t necessarily apply.
Plugins
Assuming that you have a plugin called Foo_Plugin
, it’s relatively common to see this as the last line in the plugin file:
new Foo_Plugin();
I’m guilty of doing this, but the problem is that you’re essentially creating an orphaned object. You have no way to actually access it once it’s been instantiated.
The next way that others go about resolving this is to store an instance in the $GLOBALS
collection. For example:
$GLOBALS['foo-plugin'] = new Foo_Plugin();
In this case, you can always retrieve a reference to the plugin, but some may argue that you’re polluting the $GLOBALS
collection which, depending on the size of your plugin, could be a problem, and you may accidentally overwrite an existing plugin or value that’s stored if you’re not careful for the key that you use.
Widgets
I hit on this in the introduction to the post, but arguably the most common way to to instantiate a widget is by doing the following:
add_action( 'widgets_init', create_function( '', 'register_widget( "foo_widget" );' ) );
Again, the problem is that some developers generally don’t like using anonymous function calls via create_function
to do this. The most common argument I’ve heard against this is performance.
Personally speaking, I’ve used this method since it’s what’s provided in the Codex and I’ve never really seen a performance hit.
But What About You?
And there you have it – the most common ways I’ve seen to instantiate a WordPress plugin or widget.
But I’m genuinely looking for some feedback – because I know you guys have it – on best practices not only to clarify this issue, but to improve what I do on a day-to-day basis, as well.
Leave a Reply
You must be logged in to post a comment.