php – 如何在wordpress插件中包含$wpdb?
我已经开发了一段时间在wordpress的插件,但一个问题一直困扰着我.我想将数据库表导出为ex??cel文件,因此我需要从我的插件目录中的文件访问全局$wpdb->变量.
我发现了一个博客条目,解释了我应该包含哪些类,但这不起作用(链接如下).正如你所看到的,我做了一个var_dump,但它永远不会到达那一点.如果我从代码中删除wp-config和wp-load的包含,则转储返回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(); 编辑: foreach ( wp_get_active_and_valid_plugins() as $plugin ) include_once( $plugin ); unset( $plugin ); 这是有bug的地方.我只是不知道我应该如何解决这个bug. 编辑2: global $wpdb,$table_prefix; if(!isset($wpdb)) { require_once('../../../../wp-config.php'); require_once('../../../../wp-includes/wp-db.php'); }
如果您正在创建WordPress插件,则无需手动包含这些文件.
如果要导出表,为什么不为它创建函数/类并将$wpdb传递给它(如果需要).您也可以使用普通的MySQLi级(来自PHP)来访问您的MySQL数据库. 如果您只想使用WordPress使用的存储登录值访问MySQL数据库,则可以包含WordPress根目录中的wp_config文件.它有一些(自解释)全局字段,您可以使用它们连接到您的数据库: 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()); } 之后,您将拥有一个MySQLi类的实例(如上所述),您可以使用它来访问您的数据库. 然而,我不确定这是否是完美的方式,但它确实有效. 要调试WordPress(如果某些东西不起作用且没有错误消息),你应该在wp-config.php文件中激活调试: /** * 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); 此外,如果您在本地服务器上测试PHP-Scripts,则应该在php.ini文件中将display_error设置为on: ; 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 但是,这应该仅在本地测试服务器上完成,而不是在生产方案中完成. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |