WordPress Plugin Development Strategies

Posted by & filed under Developing for WordPress, Inter, Plugins, Recommended Practices.

When you begin building a WordPress plugin, there are a lot of things you need to keep in mind: the functionality of the plugin, the target audience, how it is going to be distributed, how you are going to provide support for it, etc. There is another aspect of the development process that is often overlooked or pushed to the sidelines, and that is the set of general strategies you are going to use during your development.

When I say “general strategies”, I’m referring the things like the basic file / folder organization, the naming scheme for your files, the organization of functions within files, and the way that resources are loaded. It is best if you make an effort to keep these aspects constant throughout your development. When you use the same basic strategies for each of your projects, and throughout each individual project, you will find that it dramatically improves your workflow and the overall quality of your work.

Imagine you are writing a plugin that has upwards of 10,000 lines of code; which do you think is easier to enhance and debug, a plugin that has the 10,000 lines separated into meaningfully named files and folders, or a plugin that has all 10,000 lines in a single file? If you have answered with a single file, then I’d highly advise you to think about it a little longer, or challenge yourself to go write a very large plugin, and do it all in one file. You will quickly find that it’s highly disadvantageous.

I would like to discuss and share several aspects of my personal development strategy. Some of these are simply things that should be done because WordPress Coding Standards dictates that we should (with good reason), and some of them are strategies that I have simply found to be extremely helpful in development.

Use a Unique Prefix for Everything

This is one of the first rules of development, and it should never, ever be broken. When you write your plugin, everything absolutely must receive a unique prefix specific to your plugin. This includes function names, class names, global variables, option names, database tables and more.

The primary reason for always, without exception, using prefixes is that it prevents conflicts. If two plugins (or themes) use the same name for a function, and both are active at the same time, they will cause a fatal error, since all function names must be unique.

For example, you might have a function in your plugin like this:

load_plugin_scripts() {
    // script loading happens here
}

But this is a terrible name, because if any theme or other plugins also has a function named load_plugin_scripts, a fatal error will be thrown. Let’s imagine for a moment that your plugin is named “Load Posts with Ajax”. I usually create my prefixes by taking the first letter of each word in the plugin’s title, so our prefix will be “lpa_”, or “lpwa_”, which means our function should be this instead:

lpa_load_plugin_scripts() {
    // script loading happens here
}

Define Constants for File Paths and URLs

This mostly applies to large plugins, but can be useful with smaller ones as well. The absolute path to your plugin’s folder can be used for including extra plugin files, loading templates, and a few other things. I usually define a constant with the path to the plugin’s directory like this:

// plugin folder path
if(!defined('LPA_PLUGIN_DIR')) {
	define('LPA_PLUGIN_DIR', plugin_dir_path( __FILE__ ));
}

Remember that “LPA_” is the prefix we created for our plugin above.

It is also a good idea to define a constant for the plugin directory’s URL. This will be used for loading assets, like images, CSS files and Javascript files.

// plugin folder path
// plugin folder url
if(!defined('LPA_PLUGIN_URL')) {
	define('LPA_PLUGIN_URL', plugin_dir_url( __FILE__ ));
}

While these constants are not entirely necessary, they do make things easier in the long run. Instead of figuring out the file path or URL every time you need it, you simply call the constant. In large plugins this can save a lot of time.

Organize Your Plugin Into Multiple Files

When you are working with a plugin that has a large amount of code, then separating it into multiple files is one of the best things you can do. You should separate your code into “blocks” that are organized based on what they do. For example, all of your short code definitions should go into a file called “shortcodes.php” (or similar). All of your code that relates to loading CSS or jQuery should go into a file named perhaps “scripts.php”.

By separating your code into “blocks” that are each placed into meaningfully named files, you make your job as the developer much easier on yourself. It is suddenly dramatically easier to locate the code you’re looking for, especially when debugging errors. When you want to enhance the functionality of your plugin, perhaps by adding another short code, you immediately know where the new code should go: shortcodes.php.

With smaller plugins, this is not always the case, however. A small plugin with just 100 lines of code could easily be all placed into a single file and still be very manageable, but even in this case, I would still advise you to separate it into multiple files. The main reason for doing this is that it opens the door to further development and expansion. It is a lot easier to organize your plugin early on when there is only a small amount of code than it is to reorganize later once you have thousands of lines.

Once your plugin is separated into multiple files, you will pull the files into the main plugin file like this:

include_once( LPA_PLUGIN_DIR . 'includes/shortcodes.php' );

Note that I advise you place all of your extra files into sub directories as well. I usually place my files into a folder called “includes” (because these are included into the main file), and this directory will often have sub directories within it as well.

My plugin folder structure usually looks something like this:

  • my_plugin_folder_name
    • includes
      • admin-pages
      • templates
    • js
    • css
    • images

Format Your Code

There is very little more frustrating to a developer than opening some one else’s code and finding that it is a formatting nightmare. Messy code is usually bad code. A very simple way that you can dramatically help yourself in your development, and help anyone that works with your code, is by taking the time to format your code nicely and consistently.

Code should have even indention (I prefer tabs, not spaces) and consistent line breaks. When a chunk of code is nested inside of conditional or switch (or other) statements, it should be indented. Take this bad code for example:

if( $conditional ) {
do_action('some_action_here');
execute_some_function();
}

While there are only two lines inside of the conditional, this is still much harder to read and follow than a block that is properly indented:

if( $conditional ) {
	do_action('some_action_here');
	execute_some_function();
}

Just imagine how hard it is to read a plugin that has 100s or 1000s of lines of code that isn’t properly indented. It becomes a debugging nightmare.

Do yourself and everyone else a favor: indent and format.

Do Not Reinvent the Wheel

There are a lot of APIs and methods built into WordPress that are designed to make your job as a developer easier, so utilize them and save yourself the trouble of building your own solution.

For plugin options, use the Settings API. This API can be a bit confusing to work with at first, but once you figure it out, it is really quite simple, and extremely powerful. Tom McFarlin wrote a phenomenal tutorial series on using the Settings API, if you are unsure about it then definitely check his series out.

For showing data in your plugin in a table format (like Posts and Pages), there is a class called WP_List_Table. This class will do all of the heavy lifting for you, including pagination, filtering, bulk actions, etc, all you have to (to start at least) is provide an array of data to populate the table with.

When creating custom admin screens, make sure of core WordPress CSS. There is absolutely no reason to write dozens (or hundreds) of lines of CSS to style your custom admin pages when, instead, you could use the core styles included with WordPress. There is a pretty decent guide to admin styles at One Extra Pixel.

There are many other general strategies that you can use during development, but these alone will help you tremendously if you choose to follow them.

Tags: , ,

pippin

Pippin Williamson is a WordPress developer based in Lawrence, KS. He loves writing WordPress plugins and runs a WordPress plugin-dedicated site at Pippin's Plugins.com

26 Responses

  1. Latz July 26, 2012 at 9:02 am

    Another strategy to avoid name collisions is to wrap the code into a class. I prefer this approach because the function names are more readable without any prefixes and I don’t have to think of adding a prefix every time I create a new function.

    And since Murphy is everywhere there will be a plugin that uses the same three or four letters as a prefix.

    Reply
    • Frank July 26, 2012 at 12:22 pm

      or use namespace, but only with PHP 5.3. The namespace makes easily to use qualifid functions names and structure in your plugins.

    • pippin July 26, 2012 at 2:22 pm

      I would never say that it is overrated, since that makes it sound like there is no need to use prefixes. Don’t forget that your class names should be prefixed as well.

    • pippin July 26, 2012 at 2:11 pm

      This is definitely a very effective way of avoiding conflicts. It depends on the plugin and situation. The one thing I do not like with classes (usually), is when the entire plugin is in a single class. Assuming it’s not a really small plugin, this generally forces your entire plugin into a single file, which then can be a pain to sift through.

  2. Zane Matthew July 26, 2012 at 2:45 pm

    @pippin, Your right, the single class a.ka. God Class is a bad design decision at times.
    @frank, yes name spaces are the way to go, but as you said its not fully supported yet.
    @Fernando, I’m with you on this, prefixing (Smurf Typing) is just bad design as well.

    Reply
  3. Terry January 17, 2014 at 10:36 am

    Simply wish to say your article is as astonishing. The clearness in your post
    is just great and i could assume you are an expert on this
    subject. Fine with your permission allow me to grab your feed to
    keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.

    Reply
  4. sbobet May 5, 2014 at 6:51 am

    Spot on with this write-up, I honestly believe this web site needs a great deal more attention.

    I’ll probably be returning to read more, thanks
    for the information!

    Reply
  5. cell phone July 26, 2014 at 2:48 am

    Hey! Would you mind if I share your blog with my myspace group?
    There’s a lot of folks that I think would really enjoy your content.

    Please inform me. Cheers

    Reply
  6. Penni October 4, 2014 at 4:12 am

    Usually I don’t learn post on blogs, but I wish to say that this write-up very pressured me to try
    and do so! Your writing style has been surprised me.
    Thanks, quite great post.

    Reply
  7. old carpet October 11, 2014 at 11:21 am

    Take note, it’s not exactly the same thing, no but it is important if you own carpets with a substantial value because should something
    happen to them as a result of bad workmanship guess
    who might have to fit the bill. Now if you want a stain protector put on such as scotch guard that would cost you an additional.
    And always always always follow the manufacturer’s instructions.

    Reply

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>