Using WPDB in standalone script?

2019-01-02 15:46发布

I am trying to connect to Wordpress using the WPDB because it's such a beautiful class and also there are configurations that specified in wp-config.php so i won't need to specify it again.

I going to write a small separated script from main wordpress to run in background that will need to use this WPDB instance.

How can I archive this?

Any help is appreciated.

9条回答
初与友歌
2楼-- · 2019-01-02 16:12

Following two steps are enough.

  1. Include the wp-blog-header.php file
  2. Before using the $wpdb, put as global $wpdb;

any global variables you can use in this page after that. Make sure you give the correct include path of wp-blog-header.php. No need to include several files.

查看更多
倾城一夜雪
3楼-- · 2019-01-02 16:13

This should do the trick too:

  preg_match('/^(.+)wp-content\/.*/', dirname(__FILE__), $path);
  include($path[1] . 'wp-load.php');
查看更多
旧人旧事旧时光
4楼-- · 2019-01-02 16:23

Fast and lightweight way with just a single line is

require(dirname(_FILE__).'/wp-blog-header.php');

Reason is because wordpress initializes loading the index.php and when you check the index.php , you see :

require(dirname(__FILE__).'/wp-blog-header.php');

This loads and bootstrap wordpress.

so to use wordpress outside of the wordpress install , simply create a new file and then write :

require(dirname(__FILE__).'/wp-blog-header.php');

then for a test, write : global $wpdb; var_export($wpdb) .

so now you have access to all wordpress API and the database object $wpdb.

查看更多
登录 后发表回答