upload files dynamically to user folders

we have several users on our site. we have created a separate folder for each user. Admin have a select box to select users on the site. we have to give ability to upload files to that particular user on selection.

I have created a hook to upload_dir. its working fine with the logged in user. but how to make it dynamic on admin panel. How make this work when admin selected an user in drop down menu and upload files to that user he selected.

Read More
    function custom_upload_directory( $args ) {
        global $current_user;
        get_currentuserinfo();
        $base_directory = ABSPATH."user_documents/".$current_user->user_login;
        $base_url = home_url()."/user_documents/".$current_user->user_login;
        $args['path'] = $base_directory;
        $args['url']  = $base_url;
        $args['subdir'] = $current_user->user_login;
        $args['basedir'] = $base_directory;
        $args['baseurl'] = $base_url;return $args;
    }
    add_filter( 'upload_dir', 'custom_upload_directory' );

admin screen

upon selecting a user from drop down i have to upload a file to his folder.

dropdown code

<div id="userlistdiv" >
    <form method="post" action="">
        <h2><?php echo "users: " ?></h2>
        <select id="userselection" name="userselection">
        <?php
            $blogusers = get_users('blog_id=1&orderby=login&role=subscriber');
            echo '<option value="" selected="selected"></option>';
            foreach ($blogusers as $user) {
                echo '<option>' . $user->user_login . '</option>';
            }
        ?>
        </select>
        <INPUT TYPE="submit" name="submit" />
    </form>
</div>

Related posts

1 comment

  1. You can grab a WP_User instance with get_user_by()Codex documents that pretty well.

    add_filter( 'upload_dir', 'userLoginUploadDir' );
    function userLoginUploadDir( $args )
    {
        // Assuming that your forms user login (search? autocomplete? AJAX-ified? foo?) is named
        // name="user_login" id="user_login"
        $userLogin = esc_attr( $_GET['user_login'] );
        $user = get_user_by( 'login', $userLogin );
    
        $upload_dir = wp_upload_dir();
    
        return array_merge( $upload_dir, array(
            # 'path'    => '',
            # 'url'     => '',
            'subdir'  => $user->user_login,
            # 'basedir' => '',
            # 'baseurl' => '',
        ) );
    }
    

    Basically it should be enough to only set the specific subdir key. The rest should be available from wp_upload_dir(). In any case: Don’t use constants for pathes or URLs/URIs. Use the functions as those are applying the needed filters.

Comments are closed.