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.
require_once( ABSPATH . 'wp-load.php' );
should do the trick for you. Read some more about it herewp-load.php
? If you need an endpoint for JS queries, you can use the REST API, and if you need to run things via command line or cron, WP CLI is the correct way to do that