I suspect you don’t want to hardcode your URL to data.php
, but using a standalone file to handle requests in a theme or plugin is a major security problem.
Instead, using a REST API endpoint.
For example, lets register a data
endpoint:
add_action( 'rest_api_init', function () {
register_rest_route( 'monacoder/v1', '/data/', array(
'methods' => 'POST',
'callback' => 'monacoder_data'
) );
} );
function monacoder_data( $request ) {
return "response";
}
Now we can see that if we POST
a request to http://localhost:8080/WP/wp-json/monacoder/v1/data/
in javascript, that it responds with the value "response"
. The code can go in your functions.php
or a plugin, just make sure to have permalinks turned on.
Additionally, we can enqueue the wp-api
library:
wp_enqueue_script( 'wp-api' );
Now you have the URL available in javascript at wpApiSettings.root
, so you can do this:
jQuery.ajax({
type: "POST",
url: wpApiSettings.root + "monacoder/v1/data",
success: function() {
// do something
}
});
You can also use the wp-api
library to fetch posts, e.g:
var postsCollection = new wp.api.collections.Posts();
postsCollection.fetch();
postsCollection.forEach(function( post ) {
console.log( post );
});