Support

Account

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

Solved

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;
        }
    }
  • This code successfully changes the filename to that of the username (+.ext).

    But how can I also alter two other Image fields – namely, Caption and Alt Text? (to be user’s Full/display/nice_name, not username).

  • I would add action at the end of that code before returning the $file after you have made changes to it. Adding the filter here would insure that it is only run on images that you’ve altered the file name of. The filter is

    
    add_action('add_attachment', 'your_function_name_here');
    

    the first thing that your action should do is to remove itself so that it does not run again.

    
    remove_filter('add_attachment', 'your_function_name_here');
    

    For the rest of the action function see this https://wpkraken.io/blog/wordpress-images/, there is a code example at the end for changing the caption and alt text.

  • John, thanks for the add_attachment tip.

    I also found similar code at https://wordpress.stackexchange.com/a/310689/39300

    Whilst it assumes Post is the connected object, it also works for User.

    The following code now takes the connected User’s name and uses that also for Title and Alt fields.

    All told, now I have:

    • Filter avatars uploads to a specific folder
    • Rename uploaded avatar to match username
    • Use User’s name as attached image’s Title and Alt fields

    Thanks!

    /**
     * ==============================================================================
     *             ALSO SET IMAGE TITLE & ALT TO USER/POST NAME
     *    When an image is uploaded, use the attached Post (User) edtails
     *    to set Title, Alt fields etc.
     *    cf. https://wordpress.stackexchange.com/a/310689/39300
     *    cf. https://support.advancedcustomfields.com/forums/topic/force-an-image-file-upload-to-a-particular-directory/page/2/
     * ==============================================================================
     */
    
    // https://wordpress.stackexchange.com/a/310689/39300
    function my_set_image_meta_upon_image_upload( $post_ID ) {
    
        // "the first thing that your action should do is to remove
        // itself so that it does not run again."
        remove_filter('add_attachment', 'your_function_name_here');
    
        // Check if uploaded file is an image, else do nothing
    
        if ( wp_attachment_is_image( $post_ID ) ) {
    
            $my_image_title = get_post( $post_ID )->post_title;
    
            // Added by Robert Andrews
            // Get user name to use in image details
            $user = get_user_by( 'slug', $my_image_title );
            $user_name = $user->display_name;
            $my_image_title = $user_name;
    
            // Sanitize the title:  remove hyphens, underscores & extra spaces:
            // $my_image_title = preg_replace( '%[-_]+%', ' ',  $my_image_title );
    
            // Sanitize the title:  capitalize first letter of every word (other letters lower case):
            // $my_image_title = ucwords( strtolower( $my_image_title ) );
    
            // Create an array with the image meta (Title, Caption, Description) to be updated
            // Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
            $my_image_meta = array(
                'ID'        => $post_ID,            // Specify the image (ID) to be updated
                'post_title'    => $my_image_title,     // Set image Title to sanitized title
                // 'post_excerpt'  => $my_image_title,     // Set image Caption (Excerpt) to sanitized title
                // 'post_content'  => $my_image_title,     // Set image Description (Content) to sanitized title
            );
    
            // Set the image Alt-Text
            update_post_meta( $post_ID, '_wp_attachment_image_alt', 'Photo of '.$my_image_title );
    
            // Set the image meta (e.g. Title, Excerpt, Content)
            wp_update_post( $my_image_meta );
    
        } 
    }
Viewing 5 posts - 26 through 30 (of 30 total)

You must be logged in to reply to this topic.