WordPress – Private Upload Folder

I am creating a wp plugin which is almost like a crm system.

I wish for registered users within the backend of wordpress to be able to upload files (pdf, doc, png) and attach these files to their customer records.

Read More

I understand how to do this in terms of database and in terms of how to upload files etc.

I would like to restrict access to the files to an admin or the uploading user only. No public user or other user should be able to access these uploaded files.

Would you create a new upload folder for every user in a non-public folder and access the file only via the plugin programmatically checking the credentials?

Is there a known or better method of doing this?

Related posts

Leave a Reply

1 comment

  1. /* ===============================================
    * RESTRICT - SHOW ONLY OWN ATTACHMENTS
    =================================================*/
    
    add_filter( 'posts_where', 'o99_attachments_wpquery_where' );
    
    function o99_attachments_wpquery_where( $where ){
        global $current_user;
    
        if( is_user_logged_in() ){
            // we spreken over een ingelogde user
            if( isset( $_POST['action'] ) ){
                // library query
                if( $_POST['action'] == 'query-attachments'  && !current_user_can( 'level_10' )  ){ // o99 add optional user_can. remove if not needed
                    $where .= ' AND post_author='.$current_user->data->ID;
                }
            }
        }
    
        return $where;
    }
    

    Note – this is an example and needs to be fine – tuned according to your needs .

    Also keep in mind that the posts_where filter is very powerful and it modify the query . use with caution and remove the filter if and when it is not needed.