Support

Account

Home Forums General Issues Force an Image/File upload to a particular directory Reply To: Force an Image/File upload to a particular directory

  • Barring my if conditions being off, this is my working code for now…

    Big thanks for the help!!

    /**
     * ==============================================================================
     *             RENAME UPLOADED USER AVATAR IMAGE FILE WITH USERNAME
     *    When an image is uploaded to Edit User form through an ACF field (field_6140a6da30a17),
     *    rename file with the username of said user.
     * ==============================================================================
     */
    
    // 1. PASS USER_ID FROM USER-EDIT.PHP TO MEDIA UPLOADER, TO GET USERNAME FOR 
    // cf. https://support.advancedcustomfields.com/forums/topic/force-an-image-file-upload-to-a-particular-directory/
    // cf. https://wordpress.stackexchange.com/questions/395730/how-to-get-id-of-edit-user-page-during-wp-handle-upload-prefilter-whilst-in-med/395764?noredirect=1#comment577035_395764
    add_filter('plupload_default_params', function($params) {
        if (!function_exists('get_current_screen')) {
            return $params;
        }
        $current_screen = get_current_screen();
        if ($current_screen->id == 'user-edit') {
            $params['user_id'] = $_GET['user_id'];
        } elseif ($current_screen->id == 'profile') {
            $params['user_id'] = get_current_user_id();
        }
        return $params;
        });
    
    // 2. ON UPLOAD, DO THE RENAME
    // Filter, cf. https://wordpress.stackexchange.com/questions/168790/how-to-get-profile-user-id-when-uploading-image-via-media-uploader-on-profile-pa
    // p1: filter, p2: function to execute, p3: priority eg 10, p4: number of arguments eg 2
    add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
    function custom_upload_filter( $file ) {
        // Working with $POST contents of AJAX Media uploader
        $theuserid = $_POST['user_id'];         // Passed from user-edit.php via plupload_default_params function
        $acffield  = $_POST['_acfuploader'];    // ACF field key, inherent in $_POST
        // If user_id was present AND ACF field is for avatar Image
        if ( ($theuserid) && ($acffield=='field_6140a6da30a17') ) {
            // Get ID's username and rename file accordingly, cf. https://stackoverflow.com/a/3261107/1375163
            $user = get_userdata( $theuserid );
            $info = pathinfo($file['name']);
            $ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
            $name = basename($file['name'], $ext);
            $file['name'] = $user->user_login . $ext;
            // Carry on
            return $file;
        // Else, just use original filename
        } else {
            return $file;
        }
    }