As I already said in my previous post about WordPress Cron, few days ago, I had to export data from the WordPress database. In this article, I’m gonna tell you how to simply query your WordPress database.
Get ready for a database query
The easiest way to query your database is with the $wpdb instance, and as it is a global object, you simply have to declare is as a global variable like this.
1 2 3 4 5 |
<?php global $wpdb; ?> |
You can also use the superglobal to access the same instance, but in my opinion, it’s less readable.
In order to query another database, you will need to instantiate your own instance of the wpdb class.
Now we can write our query, it’s as simple as usual and it’s mostly in MySql, depending on your provider.
Here is an example that will return you the 5 first posts from your database.
1 2 3 4 5 |
<?php $sql = 'select * from tablePrefix_posts limit 0, 5'; ?> |
For a complete reference guide about the MySql syntax, please refer to the MySQL reference manual.
Parsing the results
Now everything is ready to perform your first query to your WordPress database, you need to parse the results to be able to exploit them. Hopefully, the wpdb class also provides a method to do it.
1 2 3 4 5 6 7 8 9 10 11 |
<?php global $wpdb; $query = 'select * from tablePrefix_posts limit 0, 5'; foreach( $wpdb->get_results( $query ) as $key => $row ) { print $row->post_title . '<br />'; } ?> |
You’re now able to query any table from your WordPress database. If you need more information about the WordPress database structure, you can refer to the WordPress Database Description in the Codex.
Security Concerns
As you may ever heard, SQL injection is also valid in the MySQL world.
MySQL injection is a type of cyberattack where malicious SQL code is inserted into a query to manipulate or access a database, potentially exposing sensitive data or compromising security.
And in this case, the wpdb class comes to the rescue, once more.
Instead of providing your query rough in the get_results method, prepare it with the … prepare method.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php global $wpdb; $limit = 5; // this could be a parameter coming from the user $query = $wpdb->prepare('select * from tablePrefix_posts limit 0, %d', $limit); foreach( $wpdb->get_results( $query ) as $key => $row ) { print $row->post_title . '<br />'; } ?> |
Good overview of how to work with $wpdb for database queries in WordPress. It would have been nice to see more about error handling in database interactions. I ended up searching for more resources to get a better grasp of that.
Clear enough explanation of how to query the database in WordPress using $wpdb.
The guide on database queries in WordPress was helpful, but I think it could have gone deeper into explaining performance optimization for large databases. Still, it gave me a good starting point for using $wpdb.