I had written some WordPress plugins last year and lately and I would like to share some of thoughts.
Before starting to write a plugin, we need to think carefully how the plugin can serve the requirements.
- “does it render any front-end code”,
- “does it need option setting page”,
- “does it need to create custom database table”,
- “does it need to use Ajax”,
There are all sorts of requirement specifications that need to be well understood to assist how plugin can be planned, implemented, troubleshooted and organized.
Once we have basic understanding of how the plugin should be acting, we also need to get familiarity of WordPress API add_action hook, do_action hook and other funcitons. WordPress has been updated quite a bit to help developer to hook some specific functions at the right moment when some action is required to be running as part of plugin functionality.
For example, assuming we need to install a custom database table for a plugin at its activation in Plugin Listing page in admin. In this case, we need to use “register_activation_hook(__FILE__,’database_install’);” to run a callback function called “database_install()” to create table defined in database_install(). If the plugin requires front-end code to be rendered, we can use “add_action(‘the_post’,’render_front_end’);” to add action where “the_post()” function (render_front_end()) is called in the page.
The following pages shows add_action and the states to hook action callback functions:
The way to organize the plugin can be simple or complex based on the actual plugin requirement. We can have individual plugin name folder to be listed in side “wp-content/plugins” to separate the plugin from others and better manage it if it has multiple files. Inside plugin folder we can use a main plugin PHP file and several other PHP files to assist functionality and implementation break-down. Moreover, CSS, js and image folders can be defined as well to better manage plugin. I recommend to have plugin Ajax folder as well to further implement plugin with Ajax support. I once read some articles about “doing WordPress Ajax in the right way”. It told us to defined Ajax code under “wp-admin/admin-ajax.php” (article: http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/). However, if we are trying to do a standalone WP plugin, this approach is not applicable. So it is better to manage everything within the plugin name folder.
In the next post, I will introduce my simple implementation of a Custom 5-Star Rating Plugin in WordPress. From there, I will do a general introduction on how to write a simple WordPress plugin (version 3.5.1).
Having in daily web/app development ^_^