The other day I came across a plugin that provided some useful functions to WordPress but is so badly coded that I can’t recommend it to anyone to use it. Though there are a lot of blog posts ranting about people “doing it wrong” this not be named plugin does so many things wrong in one place that I’m simply feeling the urge to write about a few of them.
Creating tables in the database
WordPress provides tables and, yet even better, functions to store the data of your plugin. There is for example
wp_postmeta to store data applying to a post, repectively
wp_usermeta for user data.
To store general data of your plugin you can use the wp_options table. You don’t even need to create a new row for every single piece of data but you can combine all your data into an array and use the
serialize() function to store it into a single set.
(Edit: Since version 2.0.1 it’s not necessary to seialize the data yourself because the update_* take care of it themselves.)
As you see, there is no need to create your own tables or to use your own SQL statements.
Always requesting “fresh” data
You do not need to pull data from external sources or aggregate data from the database every time your plugin is executed. There are good chances that the data you need does not change over a longer period of time. You can use some sophisticated WordPress functions to cache the data using the “Transient API”. It provides function to temporary store data (
set_transient), to retrieve it (
get_transient) and some others to control storage of temporary data.
Creating everything from scratch
WordPress contains a heap of useful functions especially for database access. So before you start connecting manually to the WordPress database take a look at the
$wpdb class which contains everything you need to coennect to the database,
add_post_meta, and other useful functions to store, alter and delete data. Take a look at them before even thinking about creating your custom SQL statement. Besides being easy to use these function assure that your plugin will work even if the database layout is changed dramatically.
After me, the deluge!
Your plugin may be the best invention since sliced bread and everyone should use it. Nevertheless be convinced that there are definitely people who test you plugin and think that there must be something better and uninstall it. So take care that your plugin does no leave any clutter in the database by deleting any trace on uninstall. On uninstall not on deactivation because a user may deactivate your plugin though he wants to continue using it, e.g. for debugging purposes, and would be happy if his options are still set upon re-activation. So be nice!
There are many other things you can do wrong ® at programming a good WordPress plugin and I hope that @nacin will create a blog about it some day.