Creating a Dynamic Path to wp-blog-header.php

Created a class in an external script which is dependent on the WordPress environment.
Since it’s a class I intend to use on various projects, I decided to dynamically create a path to wp-blog-header.php and here’s what I came up with. It currently works for me, but I need to ensure that its foolproof.

$docRoot = $_SERVER['DOCUMENT_ROOT'];
$scriptName = $_SERVER['SCRIPT_NAME'];
$queryArray = explode("https://wordpress.stackexchange.com/", $scriptName);
$queryLength = count($queryArray);

require_once($docRoot . ($queryLength > 2 ? "https://wordpress.stackexchange.com/".$queryArray[$queryLength - 2] : "" ) . '/wp-blog-header.php');

Does anyone have a better solution or is this good enough to rely on, regardless of script location or WP installation setup?

4 Answers
4

In the generic case, there is no performant solution other than to check every file and folder that is publicly accessible, and then all the parent folders.

Since this is not a feasible or excusable operation to perform on every page load or request, you’re left with two other options:

  • Define the location manually, which is not an unreasonable request
  • Make assumptions and expectations about where WordPress can be found relative to your file

The latter is what you’ll be relying on if you want to automate things.

Issues I see with your code:

  • It assumes that WordPress is either in the same folder or 2 folders up

If you’re okay with those assumptions, then yes, your code is safe to use

However I would recommend you roll your external script into WordPress as a plugin.

Leave a Comment