【发布时间】:2021-11-30 13:26:57
【问题描述】:
我正在创建一个插件。我需要从wordpress的rest api中获取一些信息,在这个链接中:http://localhost/wordpress/wp-json/wp/v2/posts 不幸的是,当我尝试从那里获取一些信息时,我的 ajax 根本不接受,因为只有 autheticats 用户才能从那里获取信息。我尝试使用此代码:
<?php
//I am trying to authenticate the user here
add_filter( 'rest_authentication_errors', 'only_authorised_rest_access');
function only_authorised_rest_access( $result )
{
if( ! is_user_logged_in() ) {
return new WP_Error( 'rest_unauthorised', __( 'Only authenticated users can access the REST API.', 'rest_unauthorised' ), array( 'status' => rest_authorization_required_code() ) );
}
return $result;
}
?>
我正在使用这个功能
<?php
function wp_favoritar_posts_init() {
$post_id = 6;
echo "<div class='redimensionar'>";
echo "<a id='teste' href='?wpfpaction=add&postid=". $post_id ."' title='teste' rel='nofollow'>Favorito</a>";
echo "</div>";
echo "<script>calculate()</script>"; //I am calling the function for take the rest api here
}
add_shortcode('favorito', 'wp_favoritar_posts_init');
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function calculate(){
var URL = "http://localhost/wordpress/wp-json/wp/v2/posts";
$.ajax({
type: "GET",
dataType: "JSON",
url: URL,
success: function(data){
alert('oi');
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
</script>
但是当我在浏览器中执行页面时,会出现以下消息:
有人建议从浏览器获取 cookie,例如对用户进行身份验证?
【问题讨论】:
-
检查您是否有防止未经授权访问 API 的插件。如此处所见wordpress.org/support/topic/…
-
这个插件叫什么名字?因为我要安装
标签: php ajax wordpress wordpress-rest-api