I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code.
I want to get information from a table I added to the database inside the header.php
file of my theme. My question is do I need to create a WordPress database connection by loading all the files like
require_once(__DIR__."/../wp-load.php");
require_once(__DIR__."/../wp-config.php");
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Or I can use the existing database connection. If I can use the existing database connection, how do I do that?
Thanks.
I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code.
I want to get information from a table I added to the database inside the header.php
file of my theme. My question is do I need to create a WordPress database connection by loading all the files like
require_once(__DIR__."/../wp-load.php");
require_once(__DIR__."/../wp-config.php");
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Or I can use the existing database connection. If I can use the existing database connection, how do I do that?
Thanks.
Share Improve this question edited Sep 19, 2019 at 10:07 fuxia♦ 107k39 gold badges255 silver badges459 bronze badges asked Sep 19, 2019 at 9:53 Real NoobReal Noob 1054 bronze badges2 Answers
Reset to default 1You can (and should) use the existing database connection by accessing global $wpdb
. The simplest way to use it is with the get_results()
method:
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM my_table' );
There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). An overview for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".
If you want to make calls to tables inside your Wordpress installation, you should always use the $wpdb
class.
https://codex.wordpress/Class_Reference/wpdb
This link shows some good examples of how to run queries to get data from tables within your Wordpress installation.