wp_ajax_nopriv_{$_REQUEST[‘action’]}
云策文档标注
概述
wp_ajax_nopriv_{$_REQUEST['action']} 是一个 WordPress Hook,用于为未登录用户触发非认证的 Ajax 动作。它允许前端 JavaScript 与服务器端 PHP 函数进行交互,处理 Ajax 请求。
关键要点
- 这是一个动态 Hook,名称中的 $_REQUEST['action'] 部分对应 Ajax 动作回调的名称。
- 主要用于处理未登录用户的 Ajax 请求,通过 add_action 绑定到服务器端函数。
- 服务器端函数应验证 nonce 和 $_POST 数据,使用 wp_json_send 或 wp_send_json 返回数据,并以 wp_die() 结束执行。
- 前端 JavaScript 通过 jQuery 的 $.post 方法发送请求,其中 action 参数需匹配 Hook 名称。
代码示例
// 服务器端 PHP 代码
add_action('wp_ajax_nopriv_front-end-action', 'server_function');
function server_function(){
// 验证 nonce 和其他 $_POST 数据,执行代码
wp_json_send($data); // 或 wp_send_json($data)
wp_die();
}
// 前端 JavaScript 代码
var data = {
'action' : 'front-end-action',
// 其他数据
};
$.post(ajaxurl, data, function(response) {
// 处理服务器响应
});注意事项
- ajaxurl 应通过 wp_localize_script 动态设置,以确保正确指向 WordPress Ajax 处理端点。
- 用户贡献笔记指出,wp_json_send($data) 可能应为 wp_send_json($data),建议查阅官方文档确认正确用法。
原文内容
Fires non-authenticated Ajax actions for logged-out users.
Description
The dynamic portion of the hook name, $_REQUEST['action'], refers to the name of the Ajax action callback being fired.
Source
'query-themes',
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 2 content
Aurovrata Venet
Used to hook an ajax action to server function when a user is not logged into the front-end,
add_action('wp_ajax_nopriv_front-end-action', 'server_function'); function server_function(){ //validate a nonce, and other $_POST data elements and execute some code. wp_json_send($data); //use wp_json_send to return some data to the client. wp_die(); //use wp_die() once you have completed your execution. }On the front-end you would have some js script executed based on some event,
//some event on the page would trigget the following var data = { 'action' : 'front-end-action', //some more data to pass to the server... }; //send the data to the server using the jQuery post method //note for the ajaxurl, its best to set it dynamically using the wp_localize_script function, see the link below $.post(ajaxurl, data, function(response) { //handle the response from the server });for more info, checkout https://developer.wordpress.org/plugins/javascript/ajax/
wp_json_send($data)should bewp_send_json($data)