Using WPDB in standalone script?

Wordpress

Wordpress Problem Overview


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.

Wordpress Solutions


Solution 1 - Wordpress

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.

Solution 2 - Wordpress

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

Solution 3 - Wordpress

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.

Solution 4 - Wordpress

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;

Solution 5 - Wordpress

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.

Solution 6 - Wordpress

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

require('the/path/to/wp-load.php file');

Solution 7 - Wordpress

This should do the trick too:

  preg_match('/^(.+)wp-content\/.*/', dirname(__FILE__), $path);
  include($path[1] . 'wp-load.php');

Solution 8 - Wordpress

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.

Solution 9 - Wordpress

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.

Solution 10 - Wordpress

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'];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDucDigitalView Question on Stackoverflow
Solution 1 - WordpressPelmeredView Answer on Stackoverflow
Solution 2 - WordpressfarinspaceView Answer on Stackoverflow
Solution 3 - WordpressMatt HumphreyView Answer on Stackoverflow
Solution 4 - WordpressAnkur21View Answer on Stackoverflow
Solution 5 - WordpressArsalan AzharView Answer on Stackoverflow
Solution 6 - WordpressSystematix InfotechView Answer on Stackoverflow
Solution 7 - WordpressOlli BolliView Answer on Stackoverflow
Solution 8 - WordpressSudharshan RamasubramaniamView Answer on Stackoverflow
Solution 9 - WordpressDevqxzView Answer on Stackoverflow
Solution 10 - WordpressRick PenabellaView Answer on Stackoverflow