问题描述
我真的不了解WordPress随机数发生了什么,我认为它们是错误的,或者它们是无用的。
我总是很难处理那个随机数,WordPess从来没有能够成功地检查一个随机数,我会在这里列出2个随机数不起作用的情况,在所有情况下我都试图提出AJAX请求:>
案例1:
在这种情况下,我尝试使用wp_rest nonce进行验证:
PHP(plugin.php):
<?php
require("ajax_endpoints.php");
class MyPluginClass {
public static function setup_plugin() {
add_shortcode("my_shortcode",array(self::class,"my_shortcode_func"));
}
public my_shortcode_func() {
// Only add scripts when this shotcode is used
self::add_plugin_scripts();
wp_enqueue_script("my_script",plugin_url("js/myscript.js",__FILE__),[],"1.0");
wp_localize_script("my_script","script_data",array(
"endpoint_url" => rest_url("/my/rest"),"endpoint_url2" => rest_url("/my/rest2"),"nonce" => wp_create_nonce("wp_rest")
));
}
}
MyPluginClass::setup_plugin();
?>
JS:
$.ajax({
url: script_data.endpoint_url,data: [],// Here is some real data
type: "post",dataType: "json",headers: {
'X-WP-Nonce': script_data.nonce
},success: () => { ... },error: () => { ... }
});
它仅在用户登录后才有效,但我没有在我的网站上使用用户,唯一的用户是admin,因此,它不适用于来宾用户(我需要为他们服务),当是访客用户时,它返回:rest_cookie_invalid_nonce 403 error
PD。我不输入ajax函数的代码,因为它甚至无法运行它们
案例2
因此,我不想在此处放置更多代码,但是,在这种情况下,在wp_create_nonce
函数中,我将wp_rest
字符串更改为any_value
字符串
在$ .ajax调用中,删除headers
选项,然后在data
选项中将现时值作为“ nonce_field”传递,在我的其余函数中,我这样做:
var_dump(check_ajax_referer("any_value","nonce_field"));
它总是返回false,nonce永远不会过去,并且还会发生:
var_dump(wp_verify_nonce($_POST["nonce_field"],"any_value"));
所以随机数永远都不是真的,我也不知道为什么,这应该是一个WordPress问题,我使用的是WordPress 5.5(最新版本),所以我认为如果它总是返回false,那么WordPress中的随机数没有用
或者您能帮我做错什么吗?非常感谢!!!
解决方法
使用wp_verify_nonce($ _POST [“ nonce_field”],“ wp_rest”);用于验证随机数。
,当您查看wp-includes / pluggable.php中的wp_verify_nonce
函数时,您会发现它是基于用户的验证。但是在您的情况下,您希望将其公开,因此在这种情况下,无需使用随机数。通过'permission_callback' => '__return_true'
函数创建自定义路由时,只需在args数组中添加register_rest_route
即可告诉WordPress该路由是公开的:
public function __construct() {
add_action( 'rest_api_init',array( $this,'registerRoutes' ),10 );
}
public function registerRoutes() {
register_rest_route(
'mybase','my/custom/path',array(
'methods' => 'POST','callback' => array( $this,'addToCart' ),'permission_callback' => '__return_true','args' => array(
'product_id' => array(
'type' => 'integer','sanitize_callback' => 'absint',),'variation_id' => array(
'type' => 'integer','quantity' => array(
'type' => 'integer',)
),)
);
}
然后只需从ajax函数中删除x-wp-nonce标头:
$.ajax({
url: script_data.endpoint_url,data: [],// Here is some real data
type: "post",dataType: "json",success: () => { ... },error: () => { ... }
});
当您向ajax请求中添加wp_verify_nonce
标头或在POST /中添加“ _wpnonce”键时,WordPress自动检查随机数(通过针对“ wp_rest”动作名称运行X-WP-Nonce
函数) GET参数/参数。