Working with databases is an essential part of WordPress development. Normally, developers use WordPress functions like WP_Query
or the REST API to get and manage data. But sometimes, you need more control.
That’s where wpdb comes in.$wpdb
is a global object in WordPress that lets you run SQL queries directly on the WordPress database. With wpdb, you can read, insert, update, and delete data in a safe and structured way.
In this guide, you’ll learn what wpdb is, how to use it with real examples, and the best practices you should follow.
Table of Contents
What is wpdb in WordPress?
- wpdb is a global object included in WordPress core.
- It is automatically available in all WordPress installations.
- It is based on the
wpdb
class and is stored in the$wpdb
variable.
With wpdb, you can connect to the WordPress database and run queries without writing raw PHP MySQLi or PDO code. This makes it powerful, but also something you must use carefully.
How to Use wpdb for Database Queries
The $wpdb
object comes with methods that make database queries easier. Let’s look at some examples (official documentantion at $wpdb at WordPress codex).
1. Database Connection
$wpdb
is already connected to your WordPress database by default. No need to set up connections manually. Just call it:
function my_function() { global $wpdb; //do something on database using $wpdb }
2. Querying the Database
You can use $wpdb
to run SQL queries. For example:
$results = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post'");
This query fetches all posts from the database.
3. The Prepare Method
Always use the prepare
method to secure your queries against SQL injection:
$user_id = 5; $user_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM wp_users WHERE ID = %d", $user_id));
4. Inserting Data:
To insert data into the database, use $wpdb->insert
:
$data = array( 'post_title' => 'Hello, World!', 'post_content' => 'This is my first post.', ); $wpdb->insert('wp_posts', $data);
5. Updating Data:
For updating, use $wpdb->update
:
$data = array('post_title' => 'Updated Title'); $where = array('ID' => 1); $wpdb->update('wp_posts', $data, $where);
6. Deleting Data:
To delete, use $wpdb->delete
:
$where = array('ID' => 1); $wpdb->delete('wp_posts', $where);
Methods of the $wpdb object
1. get_var()
The get_var()
method is a handy tool in the $wpdb
toolkit when you’re looking to retrieve a single value from the database. It simplifies the process and ensures that you get exactly what you need.
Here’s a quick breakdown:
// Example: Get the post count from the database $post_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_posts WHERE post_type = 'post'");
In this example, get_var()
is used to fetch a single value — the total count of posts with the post type ‘post’.
Key features of get_var() method
- Simplicity:
- You provide a SQL query to
get_var()
. - It executes the query and returns the first column of the first row.
- You provide a SQL query to
- Use Cases:
- Ideal for situations where you expect a single value result, like counting records or fetching a specific piece of information.
- Error Handling:
- If the query fails or doesn’t return any results,
get_var()
returnsNULL
. So, you may want to check forNULL
to handle situations where no result is found.
- If the query fails or doesn’t return any results,
Here’s an example of how you might handle errors:
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_posts WHERE post_type = 'post'"); if ($wpdb->last_error) { // Handle the error echo "Database Error: " . $wpdb->last_error; } else { // Use the $post_count value echo "Total Posts: " . $post_count; }
Why Use get_var()?
- Efficiency:
- If you only need a single value, using
get_var()
is more efficient than fetching an entire row and extracting the value.
- If you only need a single value, using
- Readability:
- It makes your code cleaner and more readable, especially when you’re dealing with simple queries.
So, whether you’re counting records, fetching IDs, or retrieving any single piece of information from your WordPress database, get_var()
is your go-to method for a quick and efficient solution.
2. get_row()
The get_row()
method is another powerful tool in the $wpdb
arsenal, designed to retrieve a single row of data from the database. This is particularly useful when you want more than a single value but still not an entire result set.
Here’s a breakdown using an example:
// Example: Get the details of the first published post $post_details = $wpdb->get_row("SELECT * FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 1");
In this example, get_row()
is used to fetch all columns of the first row from the wp_posts
table where the post status is ‘publish’, ordered by post date in descending order.
Key Features of get_row() method
- Data Retrieval:
get_row()
returns an object or an associative array containing the first row of the result set.
- Use Cases:
- Perfect for scenarios where you need more than one value but not the entire set, like fetching details of a single record.
- Error Handling:
- If the query fails or doesn’t return any results,
get_row()
returnsNULL
. Always check forNULL
to handle situations where no result is found.
- If the query fails or doesn’t return any results,
Here’s a quick example of how to handle errors:
$post_details = $wpdb->get_row("SELECT * FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 1"); if ($wpdb->last_error) { // Handle the error echo "Database Error: " . $wpdb->last_error; } elseif ($post_details) { // Use the $post_details object or array echo "Post Title: " . $post_details->post_title; echo "Post Content: " . $post_details->post_content; } else { // No results found echo "No published posts found."; }
Why Use get_row()?
- Efficiency:
- If you need more than a single value but not the entire result set, using
get_row()
is more efficient than fetching all rows and extracting the relevant one.
- If you need more than a single value but not the entire result set, using
- Flexibility:
- It provides flexibility in handling data, giving you the choice between an object or an associative array.
So, whether you’re fetching details of a user, a product, or any other single record, get_row()
is your go-to method for a concise and efficient solution.
3. get_col()
The get_col()
method is a powerful tool when you’re interested in retrieving a single column of data from the database. It simplifies the process of fetching and working with specific values.
Here’s a breakdown using an example:
// Example: Get an array of all post titles $post_titles = $wpdb->get_col("SELECT post_title FROM wp_posts WHERE post_type = 'post'");
In this example, get_col()
is used to fetch all values in the ‘post_title’ column from the wp_posts
table where the post type is ‘post’.
Key Features get_col() method
- Data Retrieval:
get_col()
returns an indexed array containing the values of the specified column.
- Use Cases:
- Ideal for scenarios where you need a list of specific values, such as retrieving all email addresses, product names, or post titles.
- Error Handling:
- If the query fails or doesn’t return any results,
get_col()
returns an empty array. Always check for the array length to handle situations where no result is found.
- If the query fails or doesn’t return any results,
Here’s an example of how to handle errors:
$post_titles = $wpdb->get_col("SELECT post_title FROM wp_posts WHERE post_type = 'post'"); if ($wpdb->last_error) { // Handle the error echo "Database Error: " . $wpdb->last_error; } elseif (!empty($post_titles)) { // Use the $post_titles array foreach ($post_titles as $title) { echo "Post Title: " . $title; } } else { // No results found echo "No posts found."; }
Why Use get_col()?
- Efficiency:
- If you only need values from a specific column, using
get_col()
is more efficient than fetching entire rows.
- If you only need values from a specific column, using
- Simplicity:
- It simplifies your code and makes it more readable, especially when you’re dealing with scenarios that require lists or arrays of specific values.
So, whether you’re creating a dropdown menu, populating a list, or working with any scenario that requires a set of specific values, get_col()
is your go-to method for a streamlined and efficient solution. Happy querying!
4. get_results()
The get_results()
method is a versatile tool that allows you to retrieve an entire result set from the database. This is handy when you need to work with multiple rows of data.
Here’s a breakdown using an example:
// Example: Get all published posts $posts = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status = 'publish'");
In this example, get_results()
is used to fetch all columns and rows from the wp_posts
table where the post status is ‘publish’.
Key Features of get_results() method
- Data Retrieval:
get_results()
returns an array of objects (by default) or an array of associative arrays, each representing a row from the result set.
- Use Cases:
- Ideal for scenarios where you need to work with multiple rows of data, such as displaying a list of blog posts, products, or users.
- Error Handling:
- If the query fails or doesn’t return any results,
get_results()
returns an empty array. Always check for the array length to handle situations where no result is found.
- If the query fails or doesn’t return any results,
Here’s an example of how to handle errors:
$posts = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status = 'publish'"); if ($wpdb->last_error) { // Handle the error echo "Database Error: " . $wpdb->last_error; } elseif (!empty($posts)) { // Use the $posts array foreach ($posts as $post) { echo "Post Title: " . $post->post_title; echo "Post Content: " . $post->post_content; } } else { // No results found echo "No published posts found."; }
Why Use get_results() ?
- Flexibility:
- It provides a comprehensive result set, giving you the flexibility to work with multiple rows and columns of data.
- Suitability:
- When you need to display or manipulate a list of items,
get_results()
is the go-to method for fetching the entire dataset efficiently.
- When you need to display or manipulate a list of items,
So, whether you’re building a dynamic page, generating a report, or handling any scenario that involves working with multiple rows of data, get_results()
is your robust solution for fetching and managing the complete result set.
Placeholders
Placeholders play a crucial role in securing your database queries and preventing SQL injection attacks. WordPress provides a method called $wpdb->prepare()
to safely format and insert data into SQL queries using placeholders.
Let’s explore how placeholders work with an example:
$user_id = 5; $user_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM wp_users WHERE ID = %d", $user_id));
In this example:
%d
is a placeholder for an integer.$user_id
is the actual value that will replace the placeholder.$wpdb->prepare()
ensures that the value is properly sanitized, preventing SQL injection.
Common Placeholders:
%d
– Integer
$user_id = 5; $wpdb->prepare("SELECT * FROM wp_users WHERE ID = %d", $user_id);
%f
– Float
$price = 19.99; $wpdb->prepare("SELECT * FROM products WHERE price = %f", $price);
%s
– String
$username = 'john_doe'; $wpdb->prepare("SELECT * FROM wp_users WHERE username = %s", $username);
%s
with Like Clause
$search_term = 'apple'; $wpdb->prepare("SELECT * FROM products WHERE product_name LIKE %s", '%' . $search_term . '%');
%s
for JSON Data (Requires WordPress 4.1+)
$json_data = json_encode(array('key' => 'value')); $wpdb->prepare("INSERT INTO wp_options (option_name, option_value) VALUES (%s, %s)", 'my_option', $json_data);
Why Use Placeholders?
- Security:
- Protects against SQL injection by automatically escaping and sanitizing input.
- Readability:
- Improves code readability by separating SQL structure from data.
- Consistency:
- Ensures that data types are correctly matched with database fields.
- Compatibility:
- Adapts queries to different database prefixes and configurations.
Remember to use placeholders whenever you’re dealing with dynamic data in your database queries. It’s a best practice that enhances both the security and maintainability of your WordPress code.
The parameters of $wpdb object
The $wpdb
object in WordPress is a global instance of the WordPress database class, and it comes with various parameters that you can use to customize its behavior. Here’s an elaboration on some of the key parameters of the $wpdb
object:
- $wpdb->prefix
- This parameter stores the database table prefix for your WordPress installation. It’s useful when you want to create dynamic queries that adapt to different database prefixes:
$table_name = $wpdb->prefix . 'custom_table';
- This parameter stores the database table prefix for your WordPress installation. It’s useful when you want to create dynamic queries that adapt to different database prefixes:
- $wpdb->base_prefix
- Similar to
$wpdb->prefix
, but it always holds the original prefix that was set when WordPress was first installed.
- Similar to
- $wpdb->charset
- The character set for the database. It’s important for internationalization and handling special characters.
- $wpdb->collate
- The collation for the database. Collation refers to the rules governing the comparison of characters in a character set.
- $wpdb->dbuser and
$wpdb->dbname
- These parameters store the username and database name, respectively, used to connect to the database.
- $wpdb->dbpassword
- The password for the database user.
- $wpdb->dbhost
- The host of the database server.
- $wpdb->dbh
- The database handle. This is the actual MySQL resource or object that represents the connection to the database.
- $wpdb->last_query
- After a query is run, this parameter holds the last SQL query executed.
- $wpdb->last_error
- If an error occurs during a query, this parameter stores the error message.
- $wpdb->num_queries
- The number of database queries made during the current WordPress execution.
- $wpdb->num_rows
- The number of rows affected by the last query (for UPDATE, DELETE, and INSERT queries).
These parameters allow you to customize your database interactions and handle different scenarios effectively. It’s important to note that many of these parameters are read-only and should be used for informational purposes rather than direct modification. For modification, you typically use the $wpdb->prepare()
method or other specific methods provided by the $wpdb
class.
Security Best Practices with wpdb
- Never insert raw user input into queries.
- Always use
$wpdb->prepare()
for dynamic values. - Use the correct data formats (
%d
for numbers,%s
for strings). - Validate and sanitize input before running queries.
These steps protect your site from SQL injection and other database attacks.
Common $wpdb Mistakes to Avoid
- Skipping prepared statements – leads to security risks.
- Not checking query results – queries can fail, so always check with
$wpdb->last_error
. - Overusing wpdb – sometimes
WP_Query
or WordPress functions are better and safer.
$wpdb vs WP_Query — When to Use Each
- Use wpdb when you need:
- Custom database tables
- Complex queries not supported by WP_Query
- Full control over SQL
- Use WP_Query when you are:
- Working with WordPress posts, pages, or custom post types
- Using standard WordPress features like taxonomies and metadata
👉 A good rule: start with WP_Query. Only use wpdb when you really need direct SQL.
Frequently Asked Questions (FAQ)
Q1: Can I use wpdb for custom database tables?
Yes. wpdb is ideal for managing custom tables, especially when building plugins.
Q2: Is wpdb deprecated in WordPress?
No. wpdb is still supported and widely used. It is safe to use as long as you follow best practices.
Q3: How can I debug wpdb queries?
You can check:
$wpdb->last_query
→ the last executed query$wpdb->last_error
→ the last error (if any)
Conclusion
The wpdb global object is one of the most powerful tools in WordPress for working directly with the database.
- It allows you to run SQL queries with methods like
get_results()
,insert()
,update()
, anddelete()
. - You should always use
$wpdb->prepare()
to keep your queries secure. - For posts and pages, WP_Query is usually the better choice, but wpdb is perfect for advanced custom work.
By learning how to use wpdb safely, you’ll gain more control over your WordPress projects and be able to build powerful custom solutions.