如何在 wordpress 中对用户进行身份验证?

Posted

技术标签:

【中文标题】如何在 wordpress 中对用户进行身份验证?【英文标题】:How to authenticate the user in the wordpress? 【发布时间】: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&amp;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/… 这个插件叫什么名字?因为我要安装 【参考方案1】:

我认为您安装了一个限制 API 访问的插件。 根据您发布的消息。

“只有经过身份验证的用户才能访问 REST API”不是错误 出现在 WordPress 核心中任何位置的消息。您是否正在使用 插件来限制对 API 的访问?

https://wordpress.org/support/topic/rest-api-not-allowing-unauthenticated-requests/

【讨论】:

这个插件叫什么名字?因为我要安装 您可能已经安装了它。因为您收到的错误并非来自核心。你应该看看你已经安装了哪些插件。

以上是关于如何在 wordpress 中对用户进行身份验证?的主要内容,如果未能解决你的问题,请参考以下文章