Creating your first WordPress plugin

By | February 2, 2011

Since I’ve been experimenting a little with WordPress plugin development, I thought it might be useful to write a simple introduction into developing a basic WordPress plugin.

Basic setup of the PHP file for your plugin (which would be called ‘my_plugin/plugin.php’):

// register the plugin activation and de-activation hooks
// you could also register a plugin class, but that's out of scope.
register_activation_hook('my_plugin/plugin.php', 'my_plugin_activate');
register_deactivation_hook('my_plugin/plugin.php', 'my_plugin_deactivate'); 

function my_plugin_activate()
{
    // you might wanna register some data into the settings of WordPress here
   $_plugin_settings = array('my_var1' => true, 'my_var2' => 'dingy');
   for ( $_plugin_settings as $name => $value )
  {
      if (!get_option($name))
         set_option($name, $value);
  }
}

function my_plugin_deactivate()
{
  // this is the place to clean-up WordPress, do not erase the settings,
  // as you might want to reinitialize the plugin without loosing the users settings.
}

With this done your plugin is able to register the settings that are needed for it to work and clean up after the user is done playing around with it. Keep in mind that you will need to set all settings you need in the activate method, otherwise you might get unexpected exceptions later on.

// register the admin menu for the plugin, you don't need to do this if there are no changable settings
add_action('admin_menu', 'wp_myplugin_admin');

function wp_myplugin_admin()
{
   add_options_page('MyPlugin', 'My plugin name',
                                            3, basename(__FILE__), 'wordpress_my_plugin_admin');
}

function wordpress_my_plugin_admin()
{
   // simple check to see if the admin settings where posted
    if ($_POST['myvar']) {
       // deal with the post request (change settings)
    }
    require_once('admin_menu.php');
}

As you can see the code block above registers an administration section for the plugin. This will enable the plugin to be configured by the end user. The PHP file ‘admin_menu.php’ basically contains the HTML code for the administration page.

You now have the basics setup, the plugin will be called every time a page is requested from WordPress. So all that is left to do is develop the code that will do your magic and you’re done.

Leave a Reply