我正在創建一個插件。我需要從 wordpress 的 rest api 中獲取一些資訊,在此鏈接中:http://localhost/wordpress/wp-json/wp/v2/posts 不幸的是,當我嘗試從那里獲取一些資訊時,我的 ajax 根本沒有接受,因為只有認證用戶才能從那里獲取資訊。我嘗試使用此代碼:
<?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,例如對用戶進行身份驗證?
uj5u.com熱心網友回復:
我認為您安裝了一個限制 API 訪問的插件。根據您發布的訊息。
“只有經過身份驗證的用戶才能訪問 REST API”不是出現在 WordPress 核心中任何地方的錯誤訊息。您是否使用插件來限制對 API 的訪問?

https://wordpress.org/support/topic/rest-api-not-allowing-unauthenticated-requests/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314705.html
標籤:php 阿贾克斯 WordPress的 wordpress-rest-api
