file custom field, upload to dynamic directory

Support Meta Box AIO file custom field, upload to dynamic directoryResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #32795
    EliodataEliodata
    Participant

    Hi,
    I would like the files uploaded via the "file" custom field to be stored into a dynamic directory with the username folder.
    This field is only enabled for specific user role, connected users. I would like the path to be like: /myfolder/%username%/
    Is it possible please?
    I am using the metabox builder.

    regards

    #32801
    Long NguyenLong Nguyen
    Moderator

    Hi,

    MB Builder does not support getting the user name to use as the custom folder name. You need to use the PHP code to get the user name and assign it to the setting upload_dir. For example, this code gets the current user name to use as a folder name.

    function your_prefix_function_name1( $meta_boxes ) {
        $current_user = wp_get_current_user();
        $user_login = $current_user->user_login;
    
        $meta_boxes[] = [
            'title'  => __( 'Post Meta1', 'your-text-domain' ),
            'id'     => 'post-meta1',
            'fields' => [
                [
                    'id'               => 'file',
                    'name'             => 'File',
                    'type'             => 'file',
                    'upload_dir'        => ABSPATH . '/myfolder/' . $user_login . '/',
                ],
            ],
        ];
        return $meta_boxes;
    }

    Get more details on the documentation
    https://docs.metabox.io/fields/file/#upload-to-custom-folder
    https://developer.wordpress.org/reference/functions/wp_get_current_user/

    #32806
    EliodataEliodata
    Participant

    Works great 🙂
    Thank you for the quick support!

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.