开发者

Wordpress single database connection

I have a separate file in root directory of my blog and i need do some oper开发者_Go百科ations with database. What i need to include in this file to work with wp database?


You will need to include this into your script before you use any global WordPress variables or functions.

define( 'WP_USE_THEMES', false );
require( '/path/to/your/wordpress/root/directory/wp-blog-header.php' );
status_header( 200 );

This will give you access to the WordPress functionality that you require such as the $wpdb global variable.


Add this function...

function get_wpdb_instance($file, $user, $pass, $name, $host='localhost') {
    $wpdb = true;
    function is_multisite() { return false; }
    function wp_die($message) {}
    require_once $file;
    return new wpdb($user, $pass, $name, $host);
}

Then in a function do the following changing the wp-db.php path as required.

$wpdb = get_wpdb_instance('../wp-includes/wp-db.php', 'username', 'password', 'database_name', 'localhost');

Then you can use $wpdb as you wish in that function...

$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM table ORDER BY id DESC LIMIT 5"), ARRAY_A);


You need to include the wp-config.php to get database informations and after simply open a connection with your db with PDO for example.

If you want to use the wpdb class, try to include "wp-includes/wp-db.php" and create a new instance of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜