How To Query Wordpress Database Using WPDB Class

Posted By : Harsh Soni | 31-Jan-2018
How to query wordpress database using $wpdb class

As we are familiar with the functions that WordPress uses to interact with the database. Some common functions are WP_Query, wp_insert_post, get_posts, update_post_meta which can be used to get the job done. But sometimes we required accessing the database directly, especially when we are going to fetch data from a custom table. Wordpress has also provided a valid way to make it easy for the users by introducing a $wpdb class.

 

Working with $wpdb Class

 

Working with $wpdb class is similar to working with MySql and other similar languages.We need to keep only few function names in mind. We can understand it by an example,

 

<?php 
global $wpdb;
   $posts = $wpdb--->get_results("SELECT post_title, post_author FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='media' DESC LIMIT 0,5");  
?>        

 

Fetching Results from the Database

 

$wpdb has four helper functions to retrieve data from the query, you can use one of four functions to structure the data.

 

GET_RESULTS() It is most commonly used function, it creates a two dimensions array of the data that contains separate objects for each row.

 

GET_ROW() When we need to fetch only one row from the database. It gives one-dimensional output.

 

GET_COL() It is similar to get_row() functions instead row it gives a single column which is helpful when we need to get only post ID.

 

GET_VAR() Sometimes we need to get only one value from the database, then we can use get_var() to retrieve a value.

 

Inserting into the Database

 

<?php             
global $wpdb;
$wpdb->insert( $table, $data, $format);
?>   
        

 

Here insert function takes three parameters. $table parameter will take name of the table. $data is an array contains a combination of key-value pairs. $format is optional which specifies the data types of the values.

 

Updating data into the Database

 

 <?php 
  global $wpdb;
  $wpdb->update($table,$data,$where,$format,$where_format);   
 ?>

 

Set the values for $table, $data and $where parameter to update the changes in database.

 

You can read more about $wpdb class and it's functions here

 

Note: The wpdb() class should not be called directly. Always use the global $wpdb object for database operations.

 

 

About Author

Author Image
Harsh Soni

Harsh is an experienced Developer with multiple tech stack such as PHP, NodeJs, Javascript, Angular. He loves learning new technologies and experimenting on them.

Request for Proposal

Name is required

Comment is required

Sending message..