Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How to include wp-load.php dynamically WordPress

  • SOLVED

I need to include wp-load.php in a few scripts like a file uploader that needs wp_upload_dir().

I've researched it myself and I know some people say not to include it because you can't dynamically find the base wp folder without a lot of hassle, however, I do need it.

The best option I found was:

$incPath = str_replace("/wp-content/themes/blahtheme/files/backend/core","",getcwd());
include($incPath.'/wp-load.php');
$uploads_dir = wp_upload_dir();


However, this creates problems if any folder name is renamed (ie: theme name) or the wp folder structure is changed.

There has to be a better way than this? I was thinking about php constant maybe?

Answers (5)

2011-02-18

Denzel Chia answers:

Hi,

This is what I used in my client's plugin to include wp-load.php
This plugin is avaliable for download in WordPress Plugins Repository.

Put the following in the beginning of your file that requires wp-load.php


//include wp-config or wp-load.php
$root = dirname(dirname(dirname(dirname(__FILE__))));
if (file_exists($root.'/wp-load.php')) {
// WP 2.6
require_once($root.'/wp-load.php');
} else {
// Before 2.6
require_once($root.'/wp-config.php');
}


It's in the file process_admin_ajax.php of this plugin http://downloads.wordpress.org/plugin/realanswers.2.1.1.zip

Thanks.

2011-02-17

Lew Ayotte answers:

Try

require_once(ABSPATH . 'wp-load.php');

By the way, check out my post on using the [[LINK href="http://lewayotte.com/2010/09/27/using-wordpress-built-in-media-upload/"]]WordPress Media upload functionality[[/LINK]]...

Lew

2011-02-17

Pippin Williamson answers:

Something like


$incPath = str_replace(ABSPATH,"",getcwd());
include($incPath.'/wp-load.php');
$uploads_dir = wp_upload_dir();


Would be better. I think that will work, though I didn't test it.

2011-02-17

John Cotton answers:

How about


$wp_load = realpath("wp-load.php");

while(!file_exists($wp_load)) {
$wp_load = '../' . $wp_load;
}

require_once($wp_load);


it might be wise to put a counter in there to stop the loop going forever (or check for the root perhaps)....

2011-02-18

Oleg Butuzov answers:


/* FindWPConfig - searching for a root of wp */
function FindWPConfig($dirrectory){
global $confroot;

foreach(glob($dirrectory."/*") as $f){

if (basename($f) == 'wp-config.php' ){
$confroot = str_replace("\\", "/", dirname($f));
return true;
}

if (is_dir($f)){
$newdir = dirname(dirname($f));
}
}

if (isset($newdir) && $newdir != $dirrectory){
if (FindWPConfig($newdir)){
return false;
}
}
return false;
}

if (!isset($table_prefix)){
global $confroot;
FindWPConfig(dirname(dirname(__FILE__)));
include_once $confroot."/wp-config.php";
include_once $confroot."/wp-load.php";
}


Oleg Butuzov comments:

i forgot to tell,, add this at begining of the file.

cheers!