Load WordPress in AJAX Environment

0

If you’re developing a plugin or theme and make use of AJAX functionality, or want to load some WordPress details in a non-Wordpress external environment, chances are you’ll be calling a PHP file that will read data or option information from the WordPress database.

However, these called files won’t be part of the WordPress Environment, and therefore have no database connectivity setup, or access to a plugin or theme’s data.

To get around this issue, include the following code at the top of any PHP file that’s not part of WordPress:

1
2
3
define('DOCUMENT_ROOT', substr(str_replace("\\", "/", dirname(__FILE__)), 0, strpos(str_replace("\\", "/", dirname(__FILE__)), "/wp-content")));
require(DOCUMENT_ROOT.'/wp-blog-header.php');
if (!have_posts()) header('HTTP/1.1 200 OK'); // Force 200 OK to replace 404 error

You can then use the standard WordPress functions and classes to access data, as if you were within a plugin or theme.

Leave a Reply

Your email address will not be published. Required fields are marked *

*