将前端视图限制为 post 作者(和管理员)

Restrict frontend view to post author (and administrator)

我有一个自定义 post 类型(审核)。我试图让每个 post 只能在前端由 post 作者和管理员查看。因此,本质上,私有 post 仅适用于匹配 post 作者 ID 和管理员的登录用户。

我已经看到很多关于如何在管理仪表板中限制 post 的答案,但是 none 对于前端,因为大多数 post 通常是 public.

非常感谢任何帮助!

我想说的是,这种方法取决于您希望用户在被拒绝访问 post 时看到的内容。您想显示一条消息说您无法查看此 post 吗?或者抛出 404?

如果您想抛出 404,可以使用 template_redirect 操作挂钩。

add_action('template_redirect', 'hide_from_unauth_users');

function hide_from_unauth_users() {

    $author = get_the_author();
    $user = wp_get_current_user();
    $is_author = "some logic to determine if this is the author";

    if( current_user_can('administrator') || ! is_user_logged_in() || ! $is_author ) {
        //throw 404 and include 404.php template
    }

}

如果您想向用户显示消息,那么您只需 运行 在实际 single.php 模板上使用完全相同的逻辑,并显示授权消息而不是 post 标题、内容等

希望这能为您指明正确的方向。