WordPress.org

Make WordPress Core

Opened 2 years ago

Closed 2 years ago

Last modified 2 years ago

#19672 closed defect (bug) (duplicate)

WP cannot be loaded through function because of variable scope

Reported by: uuf6429 Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:

Description

WP uses variable scope extensively to deliver some global variables like $wp and $wp_rewrite.

These variables are set inside wp-settings.php and assumed that the file has been included from global context.

Because of this assumption, wordpress cannot be loaded from a localized scope (such as a function).

Something like this fails:

function loadWP(){
    include 'wordpress/index.php';
}

loadWP(); // fails
include 'wordpress/index.php'; // works (assuming current file was included globally)

The first error reported is "Fatal Error: Call to a member function add_rewrite_tag() on a non-object", but this gets worse when more things dependent on these global variables simply fail.

SOLUTION

The solution is to specifically tell PHP these variables are globals. This should be done in wp-settings.php by adding the following:

global $wp_rewrite;

Before this line (line 240 in WP 3.3)

$wp_rewrite = new WP_Rewrite();

Presumably, instead you would want to have a single line at the beginning of the file like so:

global $wp_the_query, $wp_query, $wp_rewrite, $wp;

Chris.

Change History (2)

comment:1 follow-up: scribu2 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed

This has already been taken care of in WP 3.3: #17749

comment:2 in reply to: ↑ 1 ocean902 years ago

Replying to scribu:

This has already been taken care of in WP 3.3: #17749

No, 3.4: #19456.

Note: See TracTickets for help on using tickets.