在独立脚本中使用 WPDB? [英] Using WPDB in standalone script?

查看:34
本文介绍了在独立脚本中使用 WPDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

我该如何存档?

感谢任何帮助.

推荐答案

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

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

define( 'SHORTINIT', true );

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

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

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

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:

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

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

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.php and still gives you access to all the all the built in functions in WordPress core, unlike including for example /wp-includes/wp-db.php directly. 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. SHORTINIT includes the needed dependencies so you don't have to worry about this.

如果你确切地知道你需要什么,例如只有 WPDB,最快的方法当然是只包含你需要的文件,但是 SHORTINIT 提供了一种更安全、更标准化的方式来加载 WP核心和依赖.使用 SHORTINIT WordPress 不会加载插件、插件 API 的大部分、主题、主题功能以及大多数管理和前端功能.这是典型 WordPress 安装中繁重代码的所在.在大多数情况下,我认为 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 SHORTINIT provides a safer and more standardised way to load the WP core and the dependencies. With SHORTINIT WordPress 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 SHORTINIT is 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆