如何在ajax调用中使用wordpress函数

Tho*_*res 11 ajax wordpress jquery function

我想知道是否有办法在ajax调用中使用query_post()这样的函数?

假设我正在调用文件_inc/ajax.php

我想能够使用wordpress功能,但我不知道为什么.有人可以帮助我吗?

非常感谢 :)

Chr*_*s_O 30

WordPress提供了一个Ajax Url,您应该使用它与完整的Ajax API.

您需要创建一个jQuery函数.

例:

jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
Run Code Online (Sandbox Code Playgroud)

管理员端始终可以使用ajaxurl var.如果您在前端使用它,则需要定义它.

然后是一个PHP函数,您可以在其中运行查询.PHP函数必须附加到wp_ajax_your_action操作.

例:

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}
Run Code Online (Sandbox Code Playgroud)

wp_ajax_your_action如果你需要在前端使用它,那么该操作适用于adminwp_ajax_nopriv_your_action