How To Fetch Data From Database In WordPress Plugin?

Fetching data from a database is a common task in WordPress plugin development. In this article, we will cover the basic steps to fetch data from a database in a WordPress plugin.

1. Connect to the Database

Before fetching data from a database, you need to establish a connection to the database. WordPress provides a function wpdb which is a global variable that can be used to access the WordPress database.

phpCopy codeglobal $wpdb;

2. Prepare the Query

After connecting to the database, you need to prepare the SQL query to fetch data from the database. You can use the prepare() function provided by WordPress to prepare the SQL query.

phpCopy code$query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}my_table WHERE id = %d", $id );

3. Execute the Query

Once you have prepared the SQL query, you can execute it using the get_results() function provided by WordPress.

phpCopy code$results = $wpdb->get_results( $query );

4. Process the Results

After executing the SQL query, you will get the results in an array. You can then process the results as per your requirements. For example, you can loop through the results to display them on a web page.

phpCopy codeforeach ( $results as $result ) {
    echo $result->id;
    echo $result->name;

Putting It All Together

Here is an example of fetching data from a database in a WordPress plugin:

phpCopy codeglobal $wpdb;

// Set the ID of the record to fetch
$id = 1;

// Prepare the SQL query
$query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}my_table WHERE id = %d", $id );

// Execute the SQL query
$results = $wpdb->get_results( $query );

// Process the results
foreach ( $results as $result ) {
    echo $result->id;
    echo $result->name;

In the above example, we first connect to the database using the $wpdb global variable. We then prepare an SQL query to fetch a record from a custom table named my_table based on the ID. We execute the SQL query using the get_results() function and process the results using a foreach loop.


Fetching data from a database is an essential task in WordPress plugin development. By following the steps outlined in this article, you can easily fetch data from a database in your WordPress plugin. Remember to always sanitize user input and use prepared statements to prevent SQL injection attacks.

Leave a Comment