How to Easily Access the WordPress Database When Making Custom Plugins

Jacob Naryan - Full-Stack Developer

Posted: Sat Apr 01 2023

Last updated: Wed Nov 22 2023

WordPress is a great platform for web development, and a lot of the features you get with WordPress don’t require you to have any knowledge of databases. However, if you’re looking to create more custom features, you’ll often need to access the WordPress database. In this tutorial, we’ll show you how to access the WordPress database and make custom queries with just a few lines of code.

1. Access the Database with Global $wpdb

WordPress comes with a global variable called $wpdb that makes it easy to access the WordPress database. You can use this variable to make custom SQL queries and insert, update, or delete data from the WordPress database. Here’s an example of how you would use $wpdb to make a custom query:

$results = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_status = 'publish'" );

2. Inserting Data into a Basic Table

Once you’ve accessed the WordPress database, you can start inserting data into it. Here’s an example of how you would insert data into a basic table with three columns (ID, name, and email):

$wpdb->insert( 
'table_name',
array(
'ID' => 1,
'name' => 'John Smith',
'email' => 'john@example.com'
)
);

3. Updating Existing Data

If you need to update existing data in the database, you can use the $wpdb->update() function. Here’s an example of how you would use this function to update the email address for the row with the ID of 1:

$wpdb->update( 
'table_name',
array(
'email' => 'john@example.net'
),
array( 'ID' => 1 )
);

4. Deleting Data

Finally, if you need to delete data from the WordPress database, you can use the $wpdb->delete() function. Here’s an example of how you would delete the row with the ID of 1:

$wpdb->delete( 
'table_name',
array( 'ID' => 1 )
);

Conclusion

By using the global $wpdb variable, you can easily access the WordPress database and make custom queries. You can use the $wpdb->insert(), $wpdb->update(), and $wpdb->delete() functions to insert, update, and delete data from the database, respectively. With just a few lines of code, you can make custom queries and manipulate the WordPress database.

Thanks for reading, please consider tipping some BTC if you liked the blog!
Click or scan the QR code below.

bitcoin address for tips if you are so inclined.