How to run database Query in WordPress?

To run a database query in WordPress, follow these steps:

  1. Open your theme's functions.php file in a code editor.

  2. Use the $wpdb global variable to access the WordPress database.

  3. Construct your SQL query using the prepare method to sanitize and format the data.

  4. Use the $wpdb->get_results method to execute the query and retrieve the results.

Here's an example:

// Step 1: Open your theme's functions.php file

// Step 2: Use the $wpdb global variable
global $wpdb;

// Step 3: Construct your SQL query using the prepare method
$query = $wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}your_table_name WHERE column_name = %s",
    $your_variable
);

// Step 4: Use $wpdb->get_results to execute the query and retrieve results
$results = $wpdb->get_results($query);

// Step 5: Loop through the results if needed
foreach ($results as $result) {
    // Access individual result properties
    $value = $result->column_name;
    // Your code here
}

Replace your_table_name with the actual name of your database table and column_name with the specific column you want to query. Adjust the query structure based on your requirements.

Note: Always sanitize and validate user input to prevent SQL injection attacks. The prepare method in WordPress helps with this by properly escaping and formatting the data before including it in the query.