Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Wordpress

WordPress: Run Custom SQL Queries with $wpdb Object

- 06.06.26 - ErcanOPAK

💾 WP_Query Too Slow? Go Direct.

WP_Query is convenient but slow for complex reports. $wpdb runs raw SQL. 100x faster for large datasets.

📝 Basic $wpdb

global $wpdb;

// Get single value
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->users}");

// Get single row
$user = $wpdb->get_row("SELECT * FROM {$wpdb->users} WHERE ID = 123");

// Get all results (array of objects)
$users = $wpdb->get_results("SELECT * FROM {$wpdb->users} LIMIT 10");

// Insert (safe, auto-escaped)
$wpdb->insert(
    $wpdb->postmeta,
    [
        'post_id' => 123,
        'meta_key' => 'custom_field',
        'meta_value' => 'Hello World'
    ]
);

// Update
$wpdb->update(
    $wpdb->posts,
    ['post_title' => 'New Title'],
    ['ID' => 123]
);

🎯 Complex Queries

// Top 10 products by sales
$top_products = $wpdb->get_results("
    SELECT p.ID, p.post_title, SUM(oi.meta_value) as total_sales
    FROM {$wpdb->posts} p
    JOIN {$wpdb->postmeta} oi ON p.ID = oi.post_id
    WHERE p.post_type = 'product' 
      AND p.post_status = 'publish'
      AND oi.meta_key = '_order_total'
    GROUP BY p.ID
    ORDER BY total_sales DESC
    LIMIT 10
");

// Search with prepared statement (safe!)
$search = '%' . $wpdb->esc_like($search_term) . '%';
$results = $wpdb->get_results($wpdb->prepare("
    SELECT * FROM {$wpdb->posts}
    WHERE post_title LIKE %s
    AND post_status = 'publish'
", $search));

💡 Best Practices

  • Always use $wpdb->prepare() for user input (prevents SQL injection)
  • Use $wpdb->prefix for table names (multisite compatible)
  • Check for errors: if ($wpdb->last_error) { … }
  • For reports, consider caching results with transients

“WP_Query took 5 seconds for report. Raw SQL with $wpdb took 0.2 seconds. 25x faster. Know when to bypass WP_Query.”

— Performance Consultant

Related posts:

WordPress: Create Custom Taxonomies for Better Content Organization

WordPress — wp_posts Without Indexes Is a Time Bomb

How to Disable Gutenberg & Return to the Classic WordPress Editor

Post Views: 3

Post navigation

Photoshop: Use Channel Mixer for Professional Black and White Conversions
Kubernetes: Use PodDisruptionBudget to Prevent Service Interruption

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • Average of all values in a column that are not zero in SQL (538)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (505)
  • Find numbers with more than two decimal places in SQL (454)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com