javascript - How to make async query in wordpress?

admin2025-01-08  6

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.

Share Improve this question asked Dec 20, 2017 at 13:44 sal-ksal-k 32 bronze badges 3
  • 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 Commented Dec 20, 2017 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 Commented Dec 20, 2017 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 Commented Dec 20, 2017 at 14:50
Add a comment  | 

1 Answer 1

Reset to default 1

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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736266253a1106.html

最新回复(0)