WordPress Plugins and Database Interaction

Monday, May 21st, 2007 6:00 am by Ronald Huereca Print this Article Print this page Comments Comment Share This Share This

How To Write a WordPress Plugin Series

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

When you are writing a plugin, you will inevitably have to store variables in a database and retrieve them. Fortunately WordPress makes data retrieval simple with options and a database object. This post will cover storing and retrieving data from a WordPress database.

Storing Data in a Database

There are two main ways to store data in the WordPress database:

  1. Create your own table.
  2. Use Options

Since most plugins will not require their own database table, I will only cover options. However, the WordPress codex has detailed instructions on how to set up your own table.
WordPress Options

With WordPress options, saving and retrieving data from the database is as simple as a function call. WordPress has four functions for options:

  • add_option
  • get_option
  • update_option
  • delete_option

add_option

The add_option function accepts four variables, with the name of the option being required. The variables are: add_option($name, $value, $description, $autoload);

This function is beneficial for adding data to the database for retrieval later.

The $name variable should be unique so that you don't overwrite someone else's option, or someone else doesn't write over yours.

I usually don't use this function because update_option pretty much does the same thing.

get_option

The get_option function allows you to retrieve a previously stored option from the database. It accepts only one variable, which is the name of the option to retrieve. The function format is: get_option($option_name);

update_option

The update_option function works about the same as the add_option function except that it also updates an option if it already exists. I personally like the double functionality of the function and prefer it over add_option when storing data to the database.

The function format is: update_option($option_name, $new_value);

delete_option

The delete_option function deletes options from the database. The function format is: delete_option($option_name);

A Code Example

You might recall from previous posts in this series that I stored options in the database as an array. Here is a sample function followed by a brief explanation:

PHP:
  1. //Returns an array of admin options
  2. function getAdminOptions() {
  3. $devloungeAdminOptions = array('show_header' => 'true',
  4. 'add_content' => 'true',
  5. 'comment_author' => 'true',
  6. 'content' => '');
  7. $devOptions = get_option($this->adminOptionsName);
  8. if (!empty($devOptions)) {
  9. foreach ($devOptions as $key => $option)
  10. $devloungeAdminOptions[$key] = $option;
  11. }
  12. update_option($this->adminOptionsName, $devloungeAdminOptions);
  13. return $devloungeAdminOptions;
  14. }

On lines 3 - 6, I begin an associative array that will eventually be stored in the WordPress database as an option (line 12). I do this so I don't have to store multiple options (each a database call). This technique helps with code bloat, database queries, and naming collisions with other plugin authors.

The WordPress Database Class

Another powerful method of storing and retrieving data from the WordPress database is using the WordPress Database class object. In a function, a reference to the class would look like:

PHP:
  1. function sample_function() {
  2. global $wpdb;
  3. }

After this variable is referenced, you can access the many useful functions of the wpdb class.

For example, say we want to retrieve the total number of comments for our WordPress installation. Here's a function that does that using the WPDB class:

PHP:
  1. function sample_function() {
  2. global $wpdb;
  3. $comments = $wpdb->get_row("SELECT count(comment_approved) comments_count FROM $wpdb->comments where comment_approved = '1' group by comment_approved", ARRAY_A);
  4. echo $comments['comments_count'];
  5. }

Here's what the function does:

  • On line 2, we add a reference to the $wpdb variable.
  • On line 3, we call a function inside the wpdb class called get_row.
  • On line 3, we retrieve data from the comments table ($wpdb->comments).
    We specify that we want the data returned as an associative array (ARRAY_A).
  • On line 4, we echo out the result. Since I wanted the results returned as an associative array, I simply call the variable I assigned the results in SQL, which was comments_count.

The wpdb class is a very large class with a lot of functionality. I suggest heading over the WPDB Class page and looking over what the wpdb class is capable of.

Conclusion

The purpose of this post was to give you a glimpse into storing and retrieving variables from the WordPress database.

For further reading, please check out these links:

End of Article. Copyright Devlounge.
  • Post Time October 2, 2007 at 12:21 pm (permalink)

    Thank you, this is very helpful.

  • Pingback : Dr-Hamza’s Space on July 11, 2007
  • Pingback : WordPress links: uge 48 - 2007 « WordPress Tips on November 29, 2007
  • Pingback : Paige’s Blog » Blog Archive » WordPress Plugins and Database Interaction on December 7, 2007
  • Note: If you are commenting here for the first time, your comment will be sent into a moderation queue before being published. Please use your email address in order to identify yourself for your future comments. Clean XHTML: Use standards ready code tags in your comments. For example, cite a comment or phrase from an article with < blockquote > tags.

    About this author

    LoginRonald is frequently found laying his thoughts out in strong, straight-forward articles on various web related topics. He is the author of the popular WordPress plugin Ajax Edit Comments, and writes for WeblogToolsCollection and the Reader Appreciation Project. See more posts by Ronald Huereca, or visit Ronald Huereca's homepage.

    Subscribe

    SubscribeFirst time here, or frequent flyer. Whatever the case may be, we highly recommend subscribing to our feeds so you can get the latest updates without visiting the site. It's just a thought - don't say we didn't tell you so.

    Sponsors

    PSD to HTML, PSD to XHTML Service by PSD2HTML.com. You Design - We XHTML / CSS.

    Related Content

    Close
    E-mail It