Accessing Wordpress Databases

One of the more useful things I’ve learned while developing with Wordpress is the use of the $wpdb class which allows you to use the Wordpress database functions in your plugin without including the header and footer. This is useful when you’re using a bit of jQuery or AJAX to submit a form and get a call back w/o getting all the Wordpress headers and HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Wordpress root directory (from plugin's directory)
$path = '../../../';
 
include_once($path . 'wp-config.php');
include_once($path . 'wp-load.php');
include_once($path . 'wp-includes/wp-db.php');
 
function attachments() { 
    global $wpdb;
 
    $sql = "SELECT * FROM ".$wpdb->posts." WHERE post_type = 'attachment'";
    $rows = $wpdb->get_results($sql); 
    $html = '';
 
    foreach($rows as $row) { 
      $html .= '<div><a href="'.$row->guid.'">'.$row->post_title.'</a></div>';
    }
 
    return $html;
}
 
// Outputs a list of the attachments (media files)
echo attachments();
 
//