如何授权查看和点击只有登录用户才能使用的功能?

时间:2021-10-23 作者:Rodrigo Franco

我正在创建一个插件,允许用户登录到最喜欢的帖子。首先,我创建了一个短代码,用于放置在帖子中。

function add_favorite_shortcode() {
        global $post_id;
        $post_id = get_post();
        $post_id = !empty( $post_id ) ? $post_id->ID : false;
        $output = \'<div class="redimensionar"><a id="teste" href="?faction=add&amp;postid=\'. $post_id .\'" title="teste" rel="nofollow">♥ Favorito</a></div>\';
        return $output;
     }
     add_shortcode( \'favorito\', \'add_favorite_shortcode\' );
现在,我想只为登录的用户启用此功能,如何做到这一点?

我找到了这个函数,

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;
    }
    add_filter( \'rest_authentication_errors\', \'only_authorised_rest_access\');
但对我不起作用

1 个回复
最合适的回答,由SO网友:Catherine Consiglio 整理而成

如果您想对未登录的用户隐藏此短代码的输出,我将使用is_user_logged_in() function 内置在Wordpress中。

然而,正如Tom在评论中指出的那样,您将遇到的问题是,您需要检查用户是否作为运行到最喜爱帖子的操作的一部分登录。隐藏按钮实际上不会阻止用户使用该操作,除非您也保护该操作本身。