I have been researching how to create custom queries in WordPress for a potential upcoming project. What I mean by custom is the ability to query the database and display non-WordPress data on the screen. During my process of researching this and trying different things, I have discovered two things…
1. WordPress does not have the ability to easily query a table outside of it’s installation database. Or if it does I haven’t been able to find it. Everything I have read seems to point to having to merge any existing database with the WordPress installation database. This solution is not that big of deal for me.
2. WordPress DOES offer the ability to query the data that is in the installation database and display it any way you need to. I have outlined below a brief tutorial based on my findings.
This explanation uses PHP. The reason for this is because I host this on a Linux server.
The first thing we need to do is make sure our WordPress site can parse out PHP that will be inserted into a post or a page. There are several plug-ins for this. I am using EXEC-PHP. It was easy to install and I have had no issues with it.
Now that you can render PHP, let’s move on.
This example will use a very basic query based on the “users” table. However, you can use any table in the database. This should get you going in the right direction.
<?php
global $wpdb;
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->users;");?>
<p><?php echo 'user count is ' . $user_count; ?></p>
The biggest thing to note here is:
global $wpdb;
Without this line, the query won’t work. There are several things you can do with $wbdp and you can find more information here.
I know this is very basic, but this is just the beginning. I can’t really go into details of the project I am researching this for, but if the project gets the green light, there will be many more posts as I overcome the hurdles. Anyway, I hope this helps someone.


