How can I have users only see their content in WordPress?

This goes beyond posts and media. I have several CPT’s and a calendar. Is there a way to have wordpress check the user name and only show content they have created?

Related posts

Leave a Reply

3 comments

  1. In the backend, to filter all post types that are shown and restrict the visualization you can use pre_get_posts.

    add_action( 'pre_get_posts', 'users_own_content_so_12761756' );
    
    /**
     * Show only posts of the current user in the dashboard
     * affects posts, pages, media and custom post types
     */
    function users_own_content_so_12761756( $wp_query_obj ) 
    {
        // Restrict hook to the backend
        if( !is_admin() )
            return;
    
        global $current_user;
        get_currentuserinfo();
    
        // http://php.net/manual/en/function.is-a.php
        if( !is_a( $current_user, 'WP_User') )
            return;
    
        if( !current_user_can( 'administrator' ) )
            $wp_query_obj->set( 'author', $current_user->ID );
    }
    

    After applying this code, you’ll notice that the post count is not correct: it’ll show the total count and not the user count. To adjust that, refer to this Q&A: Update post counts (published, draft, unattached) in admin interface.

    You’ll need to care about user roles and capabilities as well, blocking the rights to edit someone else’s posts/pages/cpts. That’s because a user can type in the browser address example.com/wp-admin/post.php?post=POST_ID&action=edit and access the post, if he/she has the rights to do so.

  2. you can try adding this to the loop

    <?php $author = get_the_author(); 
    $current_user = wp_get_current_user(); 
    if($author != $current_user->user_nicename) {
        echo "permission denied";
        break;
    } ?>