最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Connect to database in the header of my WordPress website

programmeradmin1浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 1

You 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.

发布评论

评论列表(0)

  1. 暂无评论