66

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.

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

How can I archive this?

Any help is appreciated.

Maxime
  • 8,645
  • 5
  • 50
  • 53
DucDigital
  • 4,580
  • 9
  • 49
  • 97

11 Answers11

94

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

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;

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.

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.

Pelmered
  • 2,727
  • 21
  • 22
  • 2
    That's definitively the best answer! – Tristan CHARBONNIER May 22 '15 at 03:29
  • 2
    By far the best answer using SHORTINIT for custom scripts is a LOT faster. – Paul Phillips Jul 25 '15 at 12:29
  • 1
    Thank you! This is exactly what I needed. wp-db.php itself requires some extraneous WP functions that don't get included and this solves that. – Nick Bedford Apr 06 '16 at 03:00
  • I tried this and found that it changed my timezone setting. I looked into `wp-settings.php` and found this: `date_default_timezone_set( 'UTC' );` Quite annoying. What worries me most is that I don't know what else might also be affected. – Betty Feb 03 '19 at 02:59
54

Indeed SHORTINIT seems like the best solution: see @Pelmered answer...

For reference: SHORTINIT was introduced in WordPress 3.0 (June 17, 2010), despite not being mentioned in the release notes, having a look at the code itself provides clear indication of its addition.

<?php

$path = $_SERVER['DOCUMENT_ROOT'];

include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

// $wpdb is available, do stuff
farinspace
  • 8,422
  • 6
  • 33
  • 46
  • 24
    Isn't `wp-load.php` enough? – Matteo Riva Mar 16 '11 at 21:30
  • 2
    Yes, wp-load is enough by itself, it loads all the rest - in other words, this is loading all of WordPress including all plugins. – Brian C Mar 20 '13 at 22:47
  • When I use @farinspace code (with 2 or more `include_once()` or `require()`) in functions.php, I get `internal server error 500`!. Only one `include` or `require` works for me! – Hamid Araghi Apr 04 '19 at 13:06
23

WordPress actually allows you to use your own DBA (database abstraction layer) just by creating a file called db.php and saving it in the root of your wp-content directory.

I had the problem of needing to access a database via class I wrote, that had nothing todo with WordPress, but I didn't want to create a whole new DBA just go with this script.

Since the default WPDB does not allow you to use the factory pattern, I quickly wrote a few lines to support it, and added it to db.php...

<?php

class DB extends wpdb
{
  protected static $instance = null;

  public static function getInstance()
  {
    if (!self::$instance) {
      self::$instance = new DB(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    }

    return self::$instance;
  }
}

$wpdb = DB::getInstance();

Now when needing to use wpdb from elsewhere (in my case a non-WordPress class), you can juse use:

$wpdb = DB::getInstance();

from within a method, rather than the horrible global.

Matt Humphrey
  • 1,554
  • 1
  • 12
  • 30
  • beautiful way of getting $wpdb – hidden Jul 16 '12 at 20:57
  • Wow, where can I learn more about WordPress' DBA and db.php file? – Ben Racicot Mar 05 '15 at 03:14
  • The problem with this is the code still calls WordPress functions like apply_filter. I'm trying to find a way around having to include any other extraneous PHP files (or the whole thing). – Nick Bedford Apr 06 '16 at 02:56
  • I don't understand. How do you use it? Using the db.php file like you said from a non-WP script (as asked by the question) will get `Fatal error: Class 'wpdb' not found` – Betty Feb 03 '19 at 02:52
18

You can use $wpdb in new .php file which is inside of theme folder, by using following code.

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = $_SERVER['REQUEST_URI'];
$my_url = explode('wp-content' , $url); 
$path = $_SERVER['DOCUMENT_ROOT']."/".$my_url[0];

include_once $path . '/wp-config.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

global $wpdb;
Hamid Araghi
  • 434
  • 4
  • 15
Ankur21
  • 322
  • 3
  • 10
  • 2
    As far as I can see, this is the only way mentioned here of loading the minimum code to just use wpdb, without loading all of WordPress... – Brian C Mar 20 '13 at 22:48
5

You should just require_once('../../../wp-load.php');

And then you all WordPress classes, hooks and everything will be loaded. Now you can start to interact with the database using global $wpdb; and the wpdb instance will be started.

Maxime
  • 8,645
  • 5
  • 50
  • 53
Arsalan Azhar
  • 79
  • 1
  • 4
4

You just need to include the wp-load.php file into your script.

require('the/path/to/wp-load.php file');
KarimMesallam
  • 290
  • 8
  • 19
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31
4

This should do the trick too:

  preg_match('/^(.+)wp-content\/.*/', dirname(__FILE__), $path);
  include($path[1] . 'wp-load.php');
Olli Bolli
  • 347
  • 5
  • 15
  • 1
    Hi Hamid Araghi, basically this is not a big deal. The preg_match of dirname(__FILE__) is stored into segments into the variable $path. The tricky part can be the preg_match parameters if you are not using it too often. Please see here for a good way of testing and a cheat-sheet for the parameters at the bottom of the page: https://www.phpliveregex.com/ – Olli Bolli Apr 03 '19 at 10:24
2

Following two steps are enough.

  1. Include the wp-blog-header.php file
  2. Before using the $wpdb, put as global $wpdb;

any global variables you can use in this page after that. Make sure you give the correct include path of wp-blog-header.php. No need to include several files.

1

Fast and lightweight way with just a single line is

require(dirname(_FILE__).'/wp-blog-header.php');

Reason is because WordPress initializes loading the index.php and when you check the index.php , you see :

require(dirname(__FILE__).'/wp-blog-header.php');

This loads and bootstrap WordPress.

so to use WordPress outside of the WordPress install , simply create a new file and then write :

require(dirname(__FILE__).'/wp-blog-header.php');

then for a test, write : global $wpdb; var_export($wpdb) .

so now you have access to all WordPress API and the database object $wpdb.

Maxime
  • 8,645
  • 5
  • 50
  • 53
Devqxz
  • 51
  • 1
  • 6
0

As of June 21st, 2021 this was in their documentation, https://developer.wordpress.org/reference/classes/wpdb/, and it worked seamlessly for me:

$wpdb = $GLOBALS['wpdb'];
Rick Penabella
  • 339
  • 2
  • 10
0
<?php
// Include the WordPress bootstrap file
require_once('/path/to/wordpress/wp-load.php');

// Access the global $wpdb object
global $wpdb;

// Use $wpdb to execute a SQL query
$results = $wpdb->get_results("SELECT * FROM my_table");

// Display the results
foreach ($results as $row) {
  echo $row->column_name;
}
?>
Moxet Jan
  • 120
  • 8