Restrict frontend view to post author (and administrator)

I have a custom post type (audits). I am trying to make the each post only viewable in the frontend by the post author, and the administrator. So, essentially a private post only for logged in users that match the post author id and admin.

I’ve seen many answers for how to restrict the posts in the admin dashboard, but none for front end, since most posts are usually public.

Read More

Any help is greatly appreciated!

Related posts

1 comment

  1. I would say that the approach depends on what you want the user to see if they are denied access to the post. Would you want to display a message saying you cannot view this post? Or throw a 404?

    If you wanted to throw a 404, you could use the template_redirect action hook.

    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
        }
    
    }
    

    If you wanted to display a message to the user, then you would simply run the exact same logic above on the actual single.php template and display an authorized message instead of the post title, content, etc.

    Hope this points you in the right direction.

Comments are closed.