How to use WordPress Global Database Object ?

Share this Article

Inside this article we will discuss complete idea about WordPress Global Database Object & Core Class.

WordPress is one of the platform where we can create websites, blogs, online store and many more. Websites with static content as well as with dynamic content. WordPress provides it’s own admin panel to manage each things like page, post, products etc.

Managing wordpress pages, post and it’s contents we need a manual interface when we don’t have any idea about how can we handle with the code. Everything in wordpress is well structured, we only need to do drag and drop sections and widgets to use them.

Do you ever think those cases when we want other data instead what we look in wordpress ? Means I am talking about other data of wordpress apart from available data at admin. For custom data in wordpress we need to make queries with the database with global object in wordpress.

Let’s get started about this session into depth of wordpress core classes of database object.


What is WordPress Core Database Class?

WordPress manages almost 99% data via it’s database. Database is one of the major part of wordpress which when lost or destroyed then site will be crashed. There are 10000+ of plugins available free at wordpress repository to get any type of data from site database.

Do you want data from wordpress database as per your custom request ?

WordPress database object comes into play. It is global which can use anywhere by calling it’s methods.

To perform any database operations, WordPress provides a class called wpdb which is present in the directory at core libraries wordpress folder /wp-includes and file is /wp-includes/wp-db.php

The class “wpdb” abstracts the wordpress database functions. Most of the WordPress functions directly or indirectly use wpdb class. WordPress class wpdb based on the concept ezSQL class.

We can create an object of this wpdb class and perform all database operations but wordpress auto creates an object of this class while wordpress loads.


How to load WordPress Global Database Object ?

As we understood about wordpress database global object. So, let’s see how can we declare and use?

Already we have discussed about the core class of database, which is a class file. So we need to create an instance of wpdb class before use ? So how can we load that ? There are several abstract wordpress methods which we can use through global $wpdb object. $wpdb object is nothing, it’s an instance of wpdb class. We will see how can we use and write custom database queries.

global $wpdb;

function myFunction() {
 
   global $wpdb;
 
  //database operations - code
 
}

global is a defined keyword, we need to call when we want to use database abstract methods. There are several functions which we call by the help of $wpdb to fetch values from the database.


What are the WordPress Find or Search Methods?

We have several methods available in wordpress to find or search data. Even we can make our own custom methods. But here, we have listed some available abstract methods we use by using global $wpdb object.

  • get_var
  • get_row
  • get_col
  • get_results

get_var

The get_var function returns one value from the query. It used in application as

function myFunction(){
 
  global $wpdb; // global object of wpdb

  $wpdb->get_var("Query here");

  // Rest code here
}
// get_user_email custom function to get user email
// on the basis of id
function get_user_email(){
  
  global $wpdb;

  $email = $wpdb->get_var("SELECT user_email from ".$wpdb->prefix."users WHERE ID = 1");

  return $email;
}

When we call this get_user_email(), it will returns the user email of the user whose ID = 1.

Here, we need to understand few things. First about $wpdb->prefix and about query. Have a look into this image, you will be clear about all these.


get_row

We can use this abstract method when we need a complete row. The get_row function returns single row from the table query on the basis of some where condition.

get_row() method is very useful for complete row from a query. This method takes a user query and also a parameter with the method which is for the format of the output that should be.

It used in application as

function myFunction(){
 
  global $wpdb;

  $wpdb->get_row("Query here", Format_Parameter);

  // Rest code here
}

The first parameter of get_row() method is user query and the second parameter is one of the followings:

Example

  • OBJECT (this is the by default value) – By default get_row() method returns data into object format.
  • ARRAY_A – Result is returned into an associative array.
  • ARRAY_N – Result is returned into an numerically indexed array.
// get_user_data custom function to get all user data
// on the basis of id
function get_user_data(){
  
  global $wpdb;

  $userdata = $wpdb->get_row("SELECT * from ".$wpdb->prefix."users WHERE ID = 1");
  
  //$userdata = $wpdb->get_row("SELECT * from ".$wpdb->prefix."users WHERE ID = 1", ARRAY_A);
  
  //$userdata = $wpdb->get_row("SELECT * from ".$wpdb->prefix."users WHERE ID = 1", ARRAY_N);

  return $userdata;
}

As we call this function, get_user_data() it returns the complete row of user whose ID = 1. By default function returns data in php object format. But when we use ARRAY_A, ARRAY_N, result will be of different output format.

OBJECT – Data Output Default Format

stdClass Object
(
  [ID] => 1
  [user_login] => admin
  [user_pass] => $P$BWsoQcNmbugCw7dQOdzkCz9pkH5ctY/
  [user_nicename] => admin
  [user_email] => sample@test.com
  [user_url] => Something URL you have
  [user_registered] => 2020-07-25 06:22:13
  [user_activation_key] =>
  [user_status] => 0
  [display_name] => admin
)

ARRAY_A – Data Output format

Array
(
  [ID] => 1
  [user_login] => admin
  [user_pass] => $P$BWsoQcNmbugCw7dQOdzkCz9pkH5ctY/
  [user_nicename] => admin
  [user_email] => sample@test.com
  [user_url] => something url you have
  [user_registered] => 2020-07-25 06:22:13
  [user_activation_key] =>
  [user_status] => 0
  [display_name] => admin
)

ARRAY_N – Data Output Format

Array
(
  [0] => 1
  [1] => admin
  [2] => $P$BWsoQcNmbugCw7dQOdzkCz9pkH5ctY/
  [3] => admin
  [4] => sample@test.com
  [5] => http://localhost/woocommerce-session
  [6] => 2020-07-25 06:22:13
  [7] =>
  [8] => 0
  [9] => admin
)

get_col

This get_col() method is useful where we want to get one column value from a query. The output that we get while calling this method is an array.

So, If suppose we want to fetch all the titles of the wordpress posts surely we can use this method. The name of the method get_col() clearly indicated that we want column values.

Syntax to use get_col() method

function myFunction(){
 
  global $wpdb; // global object of wpdb

  $wpdb->get_col("Query here");

  // Rest code here
}

Example

Let’s implement this method to functions.php file. functions.php file is the wordpress functional file. So, please be aware of any changes that do in that file other wise it will break your active theme.

Let’s add this code and run that

// get_posts_title custom function to get each posts title
function get_posts_title(){
  
  global $wpdb;

  $posts_title = $wpdb->get_col("SELECT * from ".$wpdb->prefix."posts");

   return $posts_title;
}

When we call this get_posts_title(), it will returns the list of posts title in array format. It will list of titles of either page or posts. It includes both because we haven’t specified any where condition.

Here, $wpdb->prefix returns wp_ . Have a look the output format when we call the above function. Output is in array format.

Array
(
    [0] => Hello world!
    [1] => Sample Page
    [2] => Privacy Policy
    [3] => Auto Draft
    [4] => Library Tabs
)

get_results

This get_results() method is basically used to get the output of a normal generic query which has the output of multiple rows and multiple columns.

Method get_results() is basically used to get the output of a normal generic query which has the output of multiple rows and multiple columns. The default output for this method is an array of objects format. Inside each object of result set represents one row of the result set.

Syntax to use get_results() method

function myFunction(){
 
  global $wpdb; // global object of wpdb

  $wpdb->get_results("Query here", Format_Parameter);

  // Rest code here
}

The first parameter of get_results() method is user query and the second parameter is one of the followings:

Example

  • OBJECT (this is the by default value) – By default get_row() method returns data into onject format.
  • ARRAY_A – Result is returned into an associative array.
  • ARRAY_N – Result is returned into an numerically indexed array.

Example

// my_get_posts custom function to get posts
function my_get_posts(){
  
  global $wpdb;

  $all_posts = $wpdb->get_results("SELECT post_title, post_excerpt, post_status, post_type, post_name from ".$wpdb->prefix."posts limit 2");

  return $all_posts;
}

When we call this my_get_posts(), it will returns the list of posts in which we will have post_title, post_excerpt, post_status, post_type, post_name and also we have only 2 rows due to limit 2 in array format. It will list of titles of either page or posts. It includes both because we haven’t specified any where condition.

By default it uses Object as second parameter.

Array
(
    [0] => stdClass Object
        (
            [post_title] => Hello world!
            [post_excerpt] => 
            [post_status] => publish
            [post_type] => post
            [post_name] => hello-world
        )

    [1] => stdClass Object
        (
            [post_title] => Sample Page
            [post_excerpt] => 
            [post_status] => publish
            [post_type] => page
            [post_name] => sample-page
        )

)

When we change to ARRAY_A & ARRAY_N, have a look,

For ARRAY_A query will be,

$wpdb->get_results(“SELECT post_title, post_excerpt, post_status, post_type, post_name from “.$wpdb->prefix.”posts limit 2”, ARRAY_A);

Array
(
    [0] => Array
        (
            [post_title] => Hello world!
            [post_excerpt] => 
            [post_status] => publish
            [post_type] => post
            [post_name] => hello-world
        )

    [1] => Array
        (
            [post_title] => Sample Page
            [post_excerpt] => 
            [post_status] => publish
            [post_type] => page
            [post_name] => sample-page
        )

)

For ARRAY_N, query will be

$wpdb->get_results(“SELECT post_title, post_excerpt, post_status, post_type, post_name from “.$wpdb->prefix.”posts limit 2”, ARRAY_N);

Array
(
    [0] => Array
        (
            [0] => Hello world!
            [1] => 
            [2] => publish
            [3] => post
            [4] => hello-world
        )

    [1] => Array
        (
            [0] => Sample Page
            [1] => 
            [2] => publish
            [3] => page
            [4] => sample-page
        )

)

We hope this article helped you to learn about WordPress Global Database Object Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Leave a Comment

What are CSRF Functions in CodeIgniter 4 Tutorial
MySQL Stored Procedure in CodeIgniter 4 Tutorial