Include WordPress Core into own Scripts

Solution:

Short answer, do this:

define('WP_USE_THEMES', false);
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . 'wp-load.php');

Long answer, it’s a subtle gotcha around importing scripts with PHP.

If you define a local variable, outside of all functions, then it can be retrieved inside a function using ‘global’. If you have a local variable inside a function, it cannot be retrieved later using global, unless it is defined as being global there and then.

The script ‘wp-settings.php’ is where the issue lies. It is included via your call to include ‘wp-load.php’.

The variables defined there are not stated as being global; instead this is presumed because the script is always run outside of any functions, and so are automatically global. i.e.

$wordpress = 'foo';

function wordpressFunction() {
    global $wordpress;
}

Because you are importing the script within a function, they now become local variables. You are essentially doing:

function myFramework() {
    $wordpress = 'foo';

    function wordpressFunction() {
        global $wordpress;
    }
}

So the fix is to define them as global yourself before importing the script. Now $wp_query, and the others defined as global, are correctly found.