Understanding WordPress Database object $wpdb

File responsible for handling WordPress database related task is wp-includes/wp-db.php

How to create your own database class or extend the wpdb?

The file: wp-includes/load.php has a function require_wp_db() that will allow you to override the $wpdb object.

Code in the above screenshot says: load the file: wp-content/db.php, if available. This helps you to override the $wpdb object by instantiating your newly created class.

// Step 1: create a file: wp-content/db.php
// example code: db.php
<?php

if( ! defined( 'ABSPATH' ) ) exit;

class NewWpdb extends wpdb {
    public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ){
        parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );
    }
    public function new_method(){
        return 'hi from new method';
    }
}

// set the global variable $wpdb like:
$GLOBALS['wpdb'] = new NewWpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

// whichever way you prefer but just use one approach to create $wpdb object.
// $wpdb = new NewWpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

// Now you can call the new method in any template or function.
// example: put the following code in active (child) theme's functions.php
add_action( 'wp_footer', 'test' );
function test(){
    global $wpdb;
    $new_method = $wpdb->new_method();
    var_dump( $new_method ); // hi from new method.
}

Note: The initialization of object $wpdb at the end of your class declaration is very important. That is:

$wpdb = new NewWpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

Get table prefix:

global $wpdb;
$table_prefix = $wpdb->prefix;
// for multi site:
$wpdb->get_blog_prefix();

To list all database tables:

global $wpdb;
$db_tables = $wpdb->tables();
var_dump( $db_tables );
// output:
Array
(
    [users] => wp_users
    [usermeta] => wp_usermeta
    [posts] => wp_posts
    [comments] => wp_comments
    [links] => wp_links
    [options] => wp_options
    [postmeta] => wp_postmeta
    [terms] => wp_terms
    [term_taxonomy] => wp_term_taxonomy
    [term_relationships] => wp_term_relationships
    [termmeta] => wp_termmeta
    [commentmeta] => wp_commentmeta
)

Reference: WordPress wpdb Class Reference

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.