Feature
Post

Category
Code


Structure of a WordPress Plugin

How To Write a WordPress Plugin Series

This post was written as part of the How to Write a WordPress Plugin series.

One of the more important aspects of developing a WordPress plugin is how you structure it. This post will go over some tips on how to structure your plugin to organize your plugin resources and avoid naming collisions. Each plugin author is different in the way they structure a plugin, so these tips are merely my own personal preference. I’ll first briefly describe how a WordPress plugin works and then go into a plugin’s structure.

How a WordPress Plugin Works

After placing a WordPress plugin into the “wp-content/plugins/” folder, the plugin should automatically be available to install.

When a plugin is “Activated”, this tells WordPress to load your bit of code on “each” page (including admin pages). This is why if you have many plugins activated, your WordPress installation may be very slow due to the amount of code being included.

Since WordPress loads your code automatically when the plugin is activated, you can take advantage of this by tapping into the WordPress Plugin Application Program Interface (API). You can also access the WordPress template tags or create your own.

I suggest reading into the WordPress loop if you plan on making changes to the post content or comments. The WordPress loop is the loop that displays your posts. Some template tags will not work outside of this loop, so it is imperative that you know exactly where your code is executing. You can control this by taking advantage of actions and filters, which will be explained in later posts.

Folder Structure

All WordPress plugins will be installed in the wp-content/plugins directory. Some plugin authors simply include a PHP file for their plugin, but I recommend always creating a folder to store your plugin.

I typically structure my plugin in this folder structure:

  • Plugin Folder Name (The name of your plugin with no spaces or special characters)
    • Main plugin php file
    • js folder (for JavaScript files)
    • css folder (for StyleSheet files)
    • php folder (for other PHP includes)

For example purposes, here is a sample structure I have created:

  • devlounge-plugin-series
    • devlounge-plugin-series.php
    • js
    • css
    • php

Within the devlounge-plugin-series folder, I would include just the main PHP file and put all other files in their respective folders. This structure will assist other plugin authors who look at your code to be able to tell what the main plugin file is and where all the supporting files are located.

WordPress also recommends placing images in their own directory and including a read me file for your plugin.

Main Plugin File

When you start a new plugin file, the first seven lines are the lines that describe your plugin.

<?php
/* 
Plugin Name: Your Plugin Name Here
Plugin URI: Your Plugin URI
Version: Current Plugin Version
Author: Who Are You?
Description: What does your plugin do?

Line 3 allows you to name your plugin. Line 4 allows you to point a user to the web location of your plugin. Line 5 allows you to specify the current version. Line 6 allows you to specify the author of the plugin. Line 7 allows you to describe your plugin.

Shown below is an example of the code filled out:

<?php
/* 
Plugin Name: Devlounge Plugin Series
Plugin URI: http://www.devlounge.net/
Version: v1.00
Author: <a href="http://www.ronalfy.com/">Ronald Huereca</a>
Description: A sample plugin for a <a href="http://www.devlounge.net">Devlounge</a> series.

Shown below is a screenshot of what the plugin would look like in the WordPress Plugins panel.

Devlounge Plugin Screenshot

Set Up a Class Structure

You don’t have to be incredibly familiar with PHP Classes to develop a WordPress plugin, but it sure helps. A class structure is necessary in order to avoid naming collisions with other WordPress plugins. If someone out there sets up the same function name as yours in a plugin, an error will result and WordPress will be rendered inoperable until that plugin is removed.

To avoid naming collisions, it is imperative that all plugins incorporate a PHP class structure. Here is some bare-bones code that will allow you to set up a class structure.

if (!class_exists("DevloungePluginSeries")) {
	class DevloungePluginSeries {
		function DevloungePluginSeries() { //constructor
			
		}
	
	}

} //End Class DevloungePluginSeries

What the above code does is checks for the existence of a class named DevloungePluginSeries. If the class doesn’t exist, the class is created.

Initialize Your Class

The next bit of code will initialize (instantiate) your class.

if (class_exists("DevloungePluginSeries")) {
	$dl_pluginSeries = new DevloungePluginSeries();
}

All the above code checks for is if the class DevloungePluginSeries has been created. If it has, a variable called $dl_pluginSeries is created with an instance of the DevloungePluginSeries class.

Set Up Actions and Filters

The next bit of code sets up a place holder for WordPress actions and filters (which I will go over in a later post).

//Actions and Filters	
if (isset($dl_pluginSeries)) {
	//Actions
	
	//Filters
}

?>

The above code checks to make sure the $dl_pluginSeries variable is set. If it is (and that’s only if the class exists), then the appropriate actions and filters are set up.

Conclusion

The post served as a very basic foundational structure for starting a WordPress plugin. If you want to download the sample code, please feel free. The code will be available after almost every post in this series for you to dig through.

Download the Code Used In This Post

Digging through plugin code is a great way to learn the in’s and out’s of plugin design. I still do it, and I learn something new almost every time. Thank you Lewis for the tip suggestion.

For further reading, please check out these links:


  1. By inspirationbit posted on May 11, 2007 at 2:42 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    well… so far, it’s not that scary to write a plugin :-)

    I’ve got a few questions though:
    1) You’ve mentioned that we should name the “plugin with no spaces or special characters”. But then you’ve used dashes (“-”) in your sample plugin name. Does that mean that dashes are allowed, and perhaps underscores (_) are allowed as well?

    2) Should we give the SAME name to the plugin folder and the main plugin file, or can they be different?

    3) You specified that “If the class doesn’t exist, the class is created.” Do we usually have to specify what to do if the class does exist (which means our plugin is not going to work on that person’s blog, right?)?

    Thanks. Look forward to the next week’s hands-on series.

  2. By Ronald Huereca posted on May 11, 2007 at 5:14 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    inspirationbit,

    1. Dashes and underlines are okay.

    2. You do not have to use the same name, although I recommend it.

    3. If the class already exists, the plugin does not declare a new class. This is to avoid naming collisions. I wouldn’t do anything if the class exists. It’s better for the plugin to not work than for the plugin to crash a person’s WordPress blog.

    Next post is out on Sunday. Eight more to go. :)

  3. By inspirationbit posted on May 12, 2007 at 10:35 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    thanks for your answers, Ronald. Look forward to the Sunday post.

  4. By yuppicide posted on March 27, 2008 at 4:24 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Great tutorial I am reading so far. In the beginning you mention some code that is required to get started. One line is:

    4. Plugin URI: Your Plugin URI

    Shouldn’t that be URL?

  5. By TruePaige posted on May 16, 2008 at 3:50 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    yuppicide,

    URI is actually the recommended nomenclature.

    (Uniform Resource Identifier) – The address of an Internet resource. A URI is the unique name used to access the resource.

    It’s a bit of a picky different, but a URI can be much more varied, though many times it’s just a web address.

  6. By Prasanna posted on July 27, 2008 at 10:15 am
    Want an avatar? Get a gravatar! • You can link to this comment

    I loved reading your article….
    So far so good….i hope i will be able to write a plugin soon.

  7. By conor posted on April 14, 2009 at 9:29 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Great article! I am writing a mailing list plugin as i speak. Actually I have allready written it for a different CMS and am trying to convert it over… Bloody OOP! It’s going to take me a while to get to grips with it!

  8. By Dan posted on April 24, 2009 at 12:56 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Hi, could some one please help me with a problem I am having? I am following the recommended structure for building a WordPress plugin using a class, however, when I try and use the ‘add_meta_data’ code an error is generated (Warning: call_user_func(add_custom_box) [function.call-user-func]: First argument is expected to be a valid callback in C:\web\wordpress-mu\wp-admin\includes\template.php on line 2792).

    My code is not complicated, but I just cant see what I am doing wrong.

    CODE-

    array(
    “name” => “image”,
    “std” => “”,
    “title” => “Image”,
    “description” => “Using the \”Add an Image\” button, upload an image and paste the URL here.”)
    );

    function add_custom_box(){
    //global $post, $new_meta_boxes;

    /*foreach($new_meta_boxes as $meta_box) {
    $meta_box_value = get_post_meta($post->ID, $meta_box['name'].’_value’, true);

    if($meta_box_value == “”)
    $meta_box_value = $meta_box['std'];*/

    // Use nonce for verification

    echo ”;

    // The actual fields for data entry

    echo ” . __(“Description for this field”, ‘myplugin_textdomain’ ) . ‘ ‘;
    echo ”;
    }

    function create_custom_box() {
    $current_user = wp_get_current_user();
    $user_level = intval($current_user->user_level);

    if($user_level == 10) {
    if ( function_exists(‘add_meta_box’) ) {
    add_meta_box( ‘myplugin_sectionid’, __( ‘Page Settings1′, ‘myplugin_textdomain’), ‘add_custom_box’, ‘page’, ‘normal’, ‘high’ );
    }
    }

    }

    }

    }

    if (class_exists(“MultiPage”)) {
    $MultiPage = new MultiPage();
    }

    //Actions and Filters
    if (isset($MultiPage)) {
    //Actions
    add_action(‘admin_menu’, array(&$MultiPage, ‘create_custom_box’), 1);

    //Filters

    }
    ?>

  9. By Tzvethan Dichev posted on April 26, 2009 at 7:21 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Thanks. :)

  10. By Artem posted on January 12, 2010 at 7:20 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Ronald, I have a question. You say that its a good idea to use a class structure to write plugins. But how to make classes get access to all wordpress functions like wp_add_dashboard_widget() function from within the class, or other functions like wp_get_currentuser()? Seems like if you use a class, youll be troubleshooting more than writing the good stuff, and chances are that a class structure will not complete the plugin.

    Is there a wordpress class that can be extended to access all wordpress functions?

  11. TrackbackHot tipp: dodavanje kontakt forme « 3koloneDevlounge | WordPress Plugin ActionsStructure of a Wordpress Plugin Devlounge | Uniform StoresStructure of a Wordpress Plugin Devlounge | Uniform StoresEssential Wordpress Plugin Development Resources, Tutorials and Guides : Speckyboy Design MagazineWeb Design and Development usefull links | Victorelu