Last week, I wrote a post showing you how to create a custom table in the WordPress database in which to store information for your plugin. Today, I’m going to show you a few tips on how to actually work with that data.
Retrieve Rows from Your Table
Let’s say that you have created a table for your plugin, and now you need to pull information from the table. it’s quite simple actually. All we’re going to do is utilize a foreach loop to cycle through each row of the database.
1 2 3 4 | foreach( $wpdb->get_results("SELECT * FROM your_table_name;") as $key => $row) { // each column in your row will be accessible like this $my_column = $row->column_name; } |
This example will allow us to retrieve every row in the table. I use this a lot when I am wanting to display a list of all entries in a particular table. A real-world example of where this function is used, is in my Sugar Slider plugin. I used this method of retrieving data for listing all of the slides attached to a particular slider.
Retrieve a Particular Row
Let’s say now that you want to get all of the information related to a specific row in your table. You would do this, for example, when you wanted to get all of the variables defined for a particular item, such as a particular slider (following my real-world example above).
1 2 3 4 | $item_info = $wpdb->get_row("SELECT * FROM your_table_name WHERE id=8';"); // individual columns in the row may now be accessed like this: $item_info->column_name; |
These two examples will greatly increase the level of plugins you can create for WordPress. A huge number of the large-scale plugins that perform more than just a simple task utilize custom database tables for storing their information. If you want to further advance your WP plugin development, learning to work with tables like this is a must.
Later this week I will show you how to insert and remove data from your table.
Enjoy!






Hi Pippin nice tutorial!
While running it, found a minor flaw in "Retrieve a Particular Row":
At the end of line 1, you have a '; too many!
where is:
$item_info = $wpdb->get_row("SELECT * FROM your_table_name WHERE id=8';");
should be:
$item_info = $wpdb->get_row("SELECT * FROM your_table_name WHERE id=8");
Cheers!
WDMAC
- spam
- offensive
- disagree
- off topic
Like