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.

  • Ajax is by definition asynchronous (that's what the first A stands for). So if your question is whether it's possible: yes, it is. If you have a specific problem implementing it, you might want to clarify where you are struggling. – janh Dec 20 '17 at 14:27
  • I'm unsure what you mean by an async query, do you mean a non-blocking query that goes and does its stuff in the background so your PHP can continue to the next thing? – Tom J Nowell Dec 20 '17 at 14:49
  • 1
    Also, you should be using REST endpoints or WP Admin AJAX for JS requests, you should never make a call directly to a PHP file inside your theme, it's a huuge security problem – Tom J Nowell Dec 20 '17 at 14:50

Is any way to make asynchronius query to wordpress, where i can use wordpress functions?

Yes, but it's:

  • super fragile and easy to break
  • a big security problem

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 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.