如何在wordpress插件中包含$ wpdb?

Mic*_*ert 6 php wordpress plugins

我一直在开发一个在一段时间pluginwordpress,但有一个问题一直缠着我.我想将数据库表导出为ex​​cel文件,因此我需要$wpdb->variable从插件目录中的文件访问全局.

我发现了一个博客条目,解释了我应该包含哪些类,但这不起作用(链接如下).正如你所看到的,我做了一个var_dump,但它永远不会达到这一点.如果我离开代码的包含wp-config和转wp-load出,转储returns NULL,所以我猜测导入存在问题.

无论如何,我希望有人可以帮我解决这个问题.我不一定需要修复我的方法,我只需要一种方法将数据数组(从我的数据库中提取)导出到wordpress中的excel.任何帮助,将不胜感激.提前致谢.

http://www.notesbit.com/index.php/web-mysql/web-scripts/standalone-access-the-wordpress-database-using-wpdb/

include_once('../../../wp-config.php');
include_once('../../../wp-load.php');
include_once('../../../wp-includes/wp-db.php');

var_dump($wpdb);
$filter = get_where_clause();
$order = get_order_by_clause();

$data = $wpdb->get_results("SELECT * FROM " . $table_prefix . "team_data" . $filter . $order, ARRAY_A);

$result = array();
Run Code Online (Sandbox Code Playgroud)

编辑: 我不能包括wp-config,它给出了不断的错误.我知道bug发生在哪里,我只需要找到解决方法.在查看wp-settings页面(包含在wp-config中)时,您会发现以下代码行:

foreach ( wp_get_active_and_valid_plugins() as $plugin )
    include_once( $plugin );
unset( $plugin );
Run Code Online (Sandbox Code Playgroud)

这是有bug的地方.我只是不知道我应该如何解决这个bug.

编辑2: 问题解决了.当包括文件时,我wp-config不止一次(尽管我说它应该只包括一次).我使用以下代码解决了这个问题.

global $wpdb, $table_prefix;

if(!isset($wpdb))
{
    require_once('../../../../wp-config.php');
    require_once('../../../../wp-includes/wp-db.php');
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*uth 11

如果您正在创建WordPress插件,则无需手动包含这些文件.

如果要导出表,为什么不为它创建函数/类并将其传递$wpdb给它(如果需要).您也可以使用普通的MySQLi -class(来自PHP)来访问您的MySQL数据库.


如果您只想使用WordPress使用的存储登录值访问MySQL数据库,则可以wp_config在WordPress根目录中包含-file.它有一些(自解释)全局字段,您可以使用它们连接到您的数据库:

include "WP-ROOT-PATH/wp-config.php";
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Test the connection:
if (mysqli_connect_errno()){
    // Connection Error
    exit("Couldn't connect to the database: ".mysqli_connect_error());
}
Run Code Online (Sandbox Code Playgroud)

之后,您将拥有一个MySQLi类的实例(如上所述),您可以使用它来访问您的数据库.

然而,我不确定这是否是完美的方式,但它确实有效.


要调试WordPress(如果某些东西不起作用且没有错误消息),你应该在wp-config.php-file中激活调试:

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', true);
Run Code Online (Sandbox Code Playgroud)

另外,如果你是在本地服务器上测试你的PHP脚本,你应该将display_erroron您的php.ini-file:

; This directive controls whether or not and where PHP will output errors,
; notices and warnings too. Error output is very useful during development, but
; it could be very dangerous in production environments.
display_errors = On
Run Code Online (Sandbox Code Playgroud)

但是,这应该仅在本地测试服务器上完成,而不是在生产方案中完成.