Is any way to make asynchronius query to wordpress, where i can use wordpress functions?
For example:
I make in my plugin file add_post.php
which contains:
if($_POST['new_post'] == true) wp_insert_post( $_POST['post_data'] );
and using ajax I send query to execute above code.
Where wp_insert_post()
is wordpress function defined in wp-includes/post.php
.
Is any way to make asynchronius query to wordpress, where i can use wordpress functions?
For example:
I make in my plugin file add_post.php
which contains:
if($_POST['new_post'] == true) wp_insert_post( $_POST['post_data'] );
and using ajax I send query to execute above code.
Where wp_insert_post()
is wordpress function defined in wp-includes/post.php
.
Is any way to make asynchronius query to wordpress, where i can use wordpress functions?
Yes, but it's:
I strongly advise against it, and would consider the fix needed to make it work irresponsible to share.
Instead, save yourself a world of pain and use a REST API endpoint, or the official AJAX API, e.g.
// add the endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'salk/v1', '/test/', array(
'methods' => 'POST',
'callback' => 'salk_rest_test'
) );
} );
function salk_rest_test( $request ) {
// do things here
// access POST things like this $request['post_data']
// anything you return gets json encoded and sent back to the browser
}
Placed in a plugin or a themes functions file, then flushing permalinks/resaving them, use jQuery.post
with the URL example.com/wp-json/salk/v1/test/
Better yet, WordPress already provides a JS endpoint at /wp-json/wp/v2/posts
that you can use to create posts from the frontend if you're logged in with POST
requests