wp-load.php not working

I'm using require_once(../../../../wp-load.php), which is the correct relative path to the file, but it doesn't work. If I use wp-blog-header.php instead, that works and enables me to use WP functions. Any ideas as to why wp-load.php isn't working?

Thanks, Emir

Topic wp-load.php Wordpress

Category Web


You don't need to load wp-load.php, you can build an endpoint to poll with javascript using a REST API endpoint.

In your plugin, or functions.php, we're going to create an example endpoint, it will live at https://yoursite.com/wp-json/yourname/v1/yourendpoint, it will take in parameters, and reply with a snippet of JSON, just as you would expect from any other REST API.

This API will say "Hello World!".

To create it, put the following in your plugin or functions.php:

function hello() {
    return "Hello World!";
}

Then register it:

add_action( 'rest_api_init', function () {
        register_rest_route( 'yourname/v1', '/yourendpoint/', array(
                'methods' => 'GET',
                'callback' => 'hello'
        ) );
} );

Congratulations! You have a fully functioning REST API endpoint! Try visiting https://yoursite.com/wp-json/yourname/v1/yourendpoint in your browser and you'll see:

"Hello World!"

If you return an array or an object, they'll show up as the equivalent JSON.

Now, we can call this in our javascript like so:

fetch('/wp-json/yourname/v1/yourendpoint')
  .then(function(response) { return response.json();})
  .then(function(data) {
    alert(data); // outputs Hello World!
    // do stuff
  });

Or if you don't like fetch and prefer jQuery:

jQuery.ajax({
    url: '/wp-json/yourname/v1/yourendpoint'
}).done(function( data ) {
    alert( data );
    // do stuff
});

Make sure you have your permalinks turned on, remember to return data not echo it, and hey presto, you're done! This is just like any other REST API, e.g. the ones twitter, mailchimp and facebook have.

Bonus points:

  • You can pass extra fields when you create your endpoint to tell it who can access it, and which parameters you take, and it'll document it all for you and do all the checking so you don't have to ( and it'll do it correctly, so you don't have to worry about making mistakes )
  • You can use standard HTTP methods e.g. GET to get something, PUT or POST to put/push something, and DELETE to delete something
  • Don't create endpoints to return lists of posts, WordPress already has that at /wp-json/wp/v2/posts! Same with pages etc, you can create them too

But most of all, creating a PHP file in a folder, loading wp-load.php, then calling it directly, is a massive security problem, and breaks easily. Don't do that.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.