I want my wordpress website to work like mediafire. I already have an upload page that works only for logged in users. The uploaded files are saved in: uploads/username. However I want the downloads page to be unique for every user. I need a way for the page to show only the files that are in his upload directory to be shown to him (only the files in uploads/username). Any way to do that?
Asked
Active
Viewed 259 times
2 Answers
0
You can add the following code in your function.php file.
<?php
add_filter( 'ajax_query_attachments_args',
'wpb_show_current_user_attachments' );
function wpb_show_current_user_attachments( $query ) {
$user_id = get_current_user_id();
if ( $user_id && !current_user_can('activate_plugins') && !current_user_can('edit_others_posts
') ) {
$query['author'] = $user_id;
}
return $query;
}
?>
Visit this link for more details.

MohitS
- 1
-
I am sorry but I don't seem to understand what that does. Can you explain how this code helps me solve my issue? – Panos Jul 07 '22 at 09:48
-
This code uses the current_user_can function to check if the user has the capability to activate plugins or edit other users’ posts. If they don’t, then it changes the query used to display media files and limits it to the user’s ID.Like if the user's role is admin, of course, he can view others' uploads too. SO this code checks if the user role has access to activate plugin or view edit others post, then accordingly displays only their files. If this code is too much complicated for you, you can simply install this plugin. https://wordpress.org/plugins/restrict-media-library-access/ – MohitS Jul 07 '22 at 10:12
-
However how can I create a list of downloadable files in a page so the user can download his files? – Panos Jul 07 '22 at 10:22
-
Sorry but I didn't find that code helpful. – Panos Jul 07 '22 at 20:42
0
I found a wordpress question (Getting the names of all files in a directory with PHP) from where I got most of the code and then i added the user name function.
<?php
$current_user = wp_get_current_user();
$username = $current_user->user_login;
$path = "uploads/{$username}";
$files = scandir($path);
foreach ($files as &$value) {
echo "<a href='http://example.com/{$path}/".$value."' target='_blank' >".$value."</a><br/><br/>";
}
?>

Panos
- 11
- 5