wordpress 在独立脚本中使用 WPDB?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5306612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:44:56  来源:igfitidea点击:

Using WPDB in standalone script?

wordpress

提问by DucDigital

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.

我正在尝试使用 WPDB 连接到 WordPress,因为它是一个非常漂亮的类,而且 wp-config.php 中还指定了一些配置,因此我不需要再次指定它。

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

我将编写一个独立于主 WordPress 的小脚本,以便在需要使用此 WPDB 实例的后台运行。

How can I archive this?

我该如何存档?

Any help is appreciated.

任何帮助表示赞赏。

回答by Pelmered

The best(fastest and safest) way to load only load the core functionality of WordPress is to use the SHORTINITflag like this:

仅加载 WordPress 核心功能的最佳(最快和最安全)方法是使用如下SHORTINIT标志:

define( 'SHORTINIT', true );

require( '/path/to/wp-load.php' );

//Here you can use WordPress core features, for example the $WPDB object

For more information about this and see what is loaded, is to check the code in /wp-settings.php. There you will find the following section:

有关更多信息并查看加载的内容,请检查/wp-settings.php. 在那里您将找到以下部分:

// Stop most of WordPress from being loaded if we just want the basics.
if ( SHORTINIT )
    return false;

This means that anything after this won't be loaded, and it's quite a lot of things as you can see. The footprint will be much smaller than just loading the wp-load.phpand still gives you access to all the all the built in functions in WordPress core, unlike including for example /wp-includes/wp-db.phpdirectly. Many functions in WP core also has dependencies in other files and it can be a mess to figure out exactly what files you need to include to be able do what you want. SHORTINITincludes the needed dependencies so you don't have to worry about this.

这意味着在此之后的任何内容都不会被加载,正如你所看到的,它有很多东西。占用空间将比仅加载要小得多,wp-load.php并且仍然可以让您访问 WordPress 核心中的所有内置功能,而不像/wp-includes/wp-db.php直接包含在内。WP 核心中的许多函数在其他文件中也有依赖关系,要弄清楚您需要包含哪些文件才能执行您想要的操作可能会很麻烦。SHORTINIT包含所需的依赖项,因此您不必担心这一点。

If you know exactly what you need, for example only WPDB, the fastest way is of course to only include the files you need, but SHORTINITprovides a safer and more standardised way to load the WP core and the dependencies. With SHORTINITWordPress does not load plugins, most parts of the plugin API, themes, theme functions and most admin and frontend functions. This is where the heavy code is in a typical WordPress install. In most cases I think SHORTINITis worth the small tradeoff in speed/performance compared to including only the files you need and it's in most cases a huge performance boost compared to a full load.

如果你确切地知道你需要什么,例如只有 WPDB,最快的方法当然是只包含你需要的文件,但SHORTINIT提供了一种更安全、更标准化的方式来加载 WP 核心和依赖项。使用SHORTINITWordPress 不加载插件,大部分插件 API、主题、主题功能以及大多数管理和前端功能。这是典型 WordPress 安装中繁重代码的所在。在大多数情况下,我认为SHORTINIT与仅包含您需要的文件相比,在速度/性能方面进行小幅权衡是值得的,并且在大多数情况下,与满载相比,这是一个巨大的性能提升。

回答by farinspace

Indeed SHORTINITseems like the best solution: see @Pelmered answer...

确实SHORTINIT似乎是最好的解决方案:见@Pelmered答案...

For reference:SHORTINITwas introduced in WordPress 3.0 (June 17, 2010), despite not being mentioned in the release notes, having a look at the codeitself provides clear indication of its addition.

供参考:SHORTINIT在 WordPress 3.0(2010 年 6 月 17 日)中引入,尽管在发行说明中没有提到,但查看代码本身可以清楚地表明它的添加。

<?php

$path = $_SERVER['DOCUMENT_ROOT'];

include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

// $wpdb is available, do stuff

回答by Matt Humphrey

WordPress actually allows you to use your own DBA (database abstraction layer) just by creating a file called db.phpand saving it in the root of your wp-contentdirectory.

WordPress 实际上允许您使用自己的 DBA(数据库抽象层),只需创建一个名为的文件db.php并将其保存在wp-content目录的根目录中即可。

I had the problem of needing to access a database via class I wrote, that had nothing todo with WordPress, but I didn't want to create a whole new DBA just go with this script.

我遇到了需要通过我编写的类访问数据库的问题,这与 WordPress 无关,但我不想创建一个全新的 DBA,只需使用此脚本即可。

Since the default WPDBdoes not allow you to use the factory pattern, I quickly wrote a few lines to support it, and added it to db.php...

由于默认WPDB不允许你使用工厂模式,我赶紧写了几行来支持,并添加到db.php...

<?php

class DB extends wpdb
{
  protected static $instance = null;

  public static function getInstance()
  {
    if (!self::$instance) {
      self::$instance = new DB(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    }

    return self::$instance;
  }
}

$wpdb = DB::getInstance();

Now when needing to use wpdbfrom elsewhere (in my case a non-WordPress class), you can juse use:

现在,当需要wpdb从其他地方使用时(在我的情况下是非 WordPress 类),您可以使用:

$wpdb = DB::getInstance();

from within a method, rather than the horrible global.

从方法内部,而不是可怕的global.

回答by Ankur21

You can use $wpdbin new .phpfile which is inside of theme folder, by using following code.

您可以使用以下代码在主题文件夹内的$wpdb.php文件中使用。

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = $_SERVER['REQUEST_URI'];
$my_url = explode('wp-content' , $url); 
$path = $_SERVER['DOCUMENT_ROOT']."/".$my_url[0];

include_once $path . '/wp-config.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

global $wpdb;

回答by Olli Bolli

This should do the trick too:

这也应该可以解决问题:

  preg_match('/^(.+)wp-content\/.*/', dirname(__FILE__), $path);
  include($path[1] . 'wp-load.php');

回答by Arsalan Azhar

You should just require_once('../../../wp-load.php');

你应该只是 require_once('../../../wp-load.php');

And then you all WordPress classes, hooks and everything will be loaded. Now you can start to interact with the database using global $wpdb;and the wpdb instance will be started.

然后你所有的 WordPress 类、钩子和所有东西都将被加载。现在您可以开始与数据库交互,global $wpdb;wpdb 实例将启动。

回答by Systematix Infotech

You just need to include the wp-load.php file into your script.

您只需要将 wp-load.php 文件包含到您的脚本中。

require('the/path/to/wp-load.php file');

回答by Sudharshan Ramasubramaniam

Following two steps are enough.

以下两步就足够了。

  1. Include the wp-blog-header.php file
  2. Before using the $wpdb, put as global $wpdb;
  1. 包含 wp-blog-header.php 文件
  2. 在使用 $wpdb 之前,把它作为全局 $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.

之后您可以在此页面中使用的任何全局变量。确保您提供了正确的 wp-blog-header.php 包含路径。无需包含多个文件。

回答by Devqxz

Fast and lightweight way with just a single line is

只需一行即可快速轻便的方式

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

要求(目录名(_FILE__)。'/wp-blog-header.php');

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

原因是因为 WordPress 初始化加载 index.php 并且当您检查 index.php 时,您会看到:

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

要求(目录名(__FILE__)。'/wp-blog-header.php');

This loads and bootstrap WordPress.

这将加载并引导 WordPress。

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

所以要在 WordPress 安装之外使用 WordPress,只需创建一个新文件,然后编写:

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

要求(目录名(__FILE__)。'/wp-blog-header.php');

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

然后为了测试,写: global $wpdb; var_export($wpdb) 。

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

所以现在您可以访问所有 WordPress API 和数据库对象 $wpdb。