我需要从
wp-config
文件获取用户名、密码等以连接到自定义 PDO 数据库。
目前我有另一个文件,其中包含此信息,但我只想使用
wp-config
。
那么我怎样才能读取
wp-config
的不同属性呢?
我什至在 wp-config.php 中定义了自己的常量,并设法在主题中检索它们而不包含任何内容。
wp-config.php
define('DEFAULT_ACCESS', 'employee');
functions.php
echo "DEFAULT_ACCESS :".DEFAULT_ACCESS;
输出DEFAULT_ACCESS:员工
我只需包含该文件,然后我就可以访问其中的变量 varibales。
<?php
require_once 'wp-config.php';
echo DB_NAME;
?>
这是假设您位于同一服务器上,并且您可以通过文件系统访问 wp-config.php。
如果您为插件执行此操作,则这些值已经可用。您无需再次包含该文件。
这是一些相同的代码。
// ...Call the database connection settings
require "path to /wp-config.php";
// ...Connect to WP database
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ( !$dbc ) {
die( 'Not Connected: ' . mysql_error());
}
// Select the database
$db = mysql_select_db(DB_NAME);
if (!$db) {
echo "There is no database: " . $db;
}
// ...Formulate the query
$query = "
SELECT *
FROM `wp_posts`
WHERE `post_status` = 'publish'
AND `post_password` = ''
AND `post_type` = 'post'
";
// ...Perform the query
$result = mysql_query( $query );
// ...Check results of the query and terminate the script if invalid results
if ( !$result ) {
$message = '<p>Invalid query.</p>' . "\n";
$message .= '<p>Whole query: ' . $query ."</p> \n";
die ( $message );
}
// Init a variable for the number of rows of results
$num_rows = mysql_num_rows( $result );
// Print the number of posts
echo "$num_rows Posts";
// Free the resources associated with the result set
if ( $result ) {
mysql_free_result( $result );
mysql_close();
}
您可以从 wp-config.php 中获取所有全局常量,只需像这样回显常量:
<?php
echo DB_HOST;
echo DB_NAME;
echo DB_USER;
echo DB_PASSWORD;
这里是一个读取所有WP DB定义的函数:
function get_wordpress_data() {
$content = @file_get_contents( '../wp-config.php' );
if( ! $content ) {
return false;
}
$params = [
'db_name' => "/define.+?'DB_NAME'.+?'(.*?)'.+/",
'db_user' => "/define.+?'DB_USER'.+?'(.*?)'.+/",
'db_password' => "/define.+?'DB_PASSWORD'.+?'(.*?)'.+/",
'db_host' => "/define.+?'DB_HOST'.+?'(.*?)'.+/",
'table_prefix' => "/\\\$table_prefix.+?'(.+?)'.+/",
];
$return = [];
foreach( $params as $key => $value ) {
$found = preg_match_all( $value, $content, $result );
if( $found ) {
$return[ $key ] = $result[ 1 ][ 0 ];
} else {
$return[ $key ] = false;
}
}
return $return;
}
这会返回一个像这样的数组:
array (size=5)
'db_name' => string '.........'
'db_user' => string '.........'
'db_password' => string '.........'
'db_host' => string 'localhost'
'table_prefix' => string 'wp_'
如果您想连接到数据库,对于当前版本的 PHP,建议使用 mysqli 扩展(mysql 扩展将被弃用):
require_once "../wp-config.php"; // path to wp-config depends on your file locatoin
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
只需添加所需的 wp-load.php 文件即可。 您可以使用所有 WordPress 功能,例如 get_recent_posts() 以及更多...