Direct database queries let you get or change data in your WordPress site quickly. You use wpdb to talk to the database safely.
Direct database queries (wpdb) in Wordpress
$wpdb->get_results( 'SQL QUERY' ); $wpdb->get_var( 'SQL QUERY' ); $wpdb->query( 'SQL QUERY' );
Use get_results to get multiple rows as objects.
Use get_var to get a single value from the database.
Use query for insert, update, or delete operations.
$results = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_status = 'publish'" );$count = $wpdb->get_var( "SELECT COUNT(*) FROM wp_users" );$wpdb->query( "UPDATE wp_options SET option_value = 'blue' WHERE option_name = 'site_color'" );This code gets the latest 3 published post titles from the WordPress database and prints them line by line.
<?php // Access the global wpdb object global $wpdb; // Get the titles of the 3 most recent published posts $recent_posts = $wpdb->get_results( "SELECT post_title FROM {$wpdb->prefix}posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 3" ); // Print each post title foreach ($recent_posts as $post) { echo $post->post_title . "\n"; } ?>
Always use $wpdb->prefix to get the correct table prefix for your site.
Use prepared statements with $wpdb->prepare() to avoid SQL injection risks.
Direct queries bypass WordPress caching, so use them carefully to avoid performance issues.
wpdb lets you run SQL queries directly on the WordPress database.
Use get_results, get_var, and query for different query types.
Always write safe queries using $wpdb->prepare() and the table prefix.
Practice
$wpdb object in WordPress?Solution
Step 1: Understand the role of
$wpdb$wpdbis a WordPress class that allows running SQL queries directly on the database.Step 2: Identify the correct purpose
It is used to safely execute SQL queries, not for posts, sessions, or styling.Final Answer:
To run direct SQL queries on the WordPress database safely -> Option DQuick Check:
$wpdb= direct database queries [OK]
$wpdb is for database queries only [OK]- Confusing
$wpdbwith theme or user management - Thinking
$wpdbhandles styling or sessions
$wpdb?Solution
Step 1: Identify the safe query method
$wpdb->prepare()safely inserts variables into SQL queries using placeholders like %d.Step 2: Check each option
$wpdb->prepare("SELECT * FROM wp_posts WHERE ID = %d", $id); usespreparecorrectly with %d and variable $id. Others either lack preparation or use wrong methods.Final Answer:
$wpdb->prepare("SELECT * FROM wp_posts WHERE ID = %d", $id); -> Option AQuick Check:
Safe query usespreparewith placeholders [OK]
prepare with %d, %s for safe queries [OK]- Inserting variables directly without prepare
- Using wrong method names like execute
- Not using placeholders for variables
wp_users table has 3 users?$count = $wpdb->get_var("SELECT COUNT(*) FROM wp_users");Solution
Step 1: Understand
get_varusageget_varreturns a single value from the database, here the count of users.Step 2: Interpret the SQL query
The query counts rows inwp_users, which is 3 users.Final Answer:
The number 3 -> Option BQuick Check:
get_varreturns single value count [OK]
get_var returns one value, not arrays [OK]- Expecting an array instead of a single value
- Confusing
get_varwithget_results - Thinking it returns true/false
$results = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status = 'publish'");
foreach($results as $post) {
echo $post->post_title;
}Solution
Step 1: Check query safety
The query uses a fixed string 'publish' so no variable injection risk, soprepareis not required here.Step 2: Analyze method and loop
get_resultsreturns an array of objects; looping with$postis correct. No syntax error here.Final Answer:
No error; code works correctly -> Option CQuick Check:
Fixed string query is safe withoutprepare[OK]
prepare when variables are in query [OK]- Ignoring query preparation for dynamic inputs
- Confusing
get_resultswithquery - Misusing loop variables
$post_id safely using $wpdb. Which code snippet correctly does this?Solution
Step 1: Understand safe update with
Use$wpdbprepareto safely insert variables, then runquerywith prepared SQL.Step 2: Check each option
$prepared = $wpdb->prepare("UPDATE wp_posts SET post_title = %s WHERE ID = %d", $new_title, $post_id); $wpdb->query($prepared); correctly prepares the query and then runs it. $wpdb->prepare("UPDATE wp_posts SET post_title = %s WHERE ID = %d", $new_title, $post_id); $wpdb->query($prepared); callspreparebut does not assign or run the result properly. $wpdb->query("UPDATE wp_posts SET post_title = '$new_title' WHERE ID = $post_id"); is unsafe. $wpdb->update('wp_posts', ['post_title' => $new_title], ['ID' => $post_id]); usesupdatemethod but misses table prefix and is not asked here.Final Answer:
$prepared = $wpdb->prepare("UPDATE wp_posts SET post_title = %s WHERE ID = %d", $new_title, $post_id); $wpdb->query($prepared); -> Option AQuick Check:
Prepare query, assign, then query [OK]
prepare result before running query [OK]- Running
preparewithout assigning result - Inserting variables directly into SQL
- Confusing
updatemethod usage
Ready to prove it?
Pass the test and this pattern moves unknown
