Home > Enterprise >  How do I change the path of the wordpress image upload directory?
How do I change the path of the wordpress image upload directory?

Time:08-21

I have a function that saves images uploaded by users in a separate directory from the default one. Currently the images are saved in wp-contents / uploads / avatar-upload. How can I change this path?

Actually I would like to save them outside the uploads folder, for example in wp-contents / avatar-upload.

Can anyone help me and show me the right way for this? I appreciate any help and thank you for any replies.

// Save Avatar Action
function action_woocommerce_save_account_details( $user_id ) {  
  if ( isset( $_FILES['image'] ) ) {
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    // Set custom upload folder
    function wp_set_custom_upload_folder($uploads) {
        $uploads['path'] = $uploads['basedir'] . '/avatar-upload';
        $uploads['url'] = $uploads['baseurl'] . '/avatar-upload';    
        if (!file_exists($uploads['path'])) {
          mkdir($uploads['path'], 0755, true);
        }
        return $uploads;
    }
    add_filter('upload_dir', 'wp_set_custom_upload_folder');    
      
    $attachment_id = media_handle_upload( 'image', 0 );

    if ( is_wp_error( $attachment_id ) ) {
      update_user_meta( $user_id, 'image', $_FILES['image']['error'] . ": " . $attachment_id->get_error_message() );

    } else {
      $old_attachment_id = get_user_meta( $user_id, 'image', true );
      wp_delete_attachment($old_attachment_id);
      update_user_meta( $user_id, 'image', $attachment_id );
    } 

    remove_filter('upload_dir', 'wp_set_custom_upload_folder');
  }

}
add_action( 'woocommerce_save_account_details', 'action_woocommerce_save_account_details', 10, 1 );

CodePudding user response:

Here's a re-write of the internal function wp_set_custom_upload_folder which will allow you to upload the files anywhere:

// Set custom upload folder
function wp_set_custom_upload_folder($uploads) {
    //Use a variable to hold custom directory path. Make sure to use / at the beginning.
    $uploadDir = 'wp-content/avatar-upload';

    //Use ABSPATH to get the root directory
    $uploads['path'] = ABSPATH . $uploadDir;
    //Use site_url() to get the URL of the website up to that directory.
    $uploads['url'] = site_url('/'.$uploadDir);

    //Note: ABSPATH and site_url() don't output a trailing slash
   
    $uploads['basedir'] =  ABSPATH . 'wp-content'; 
    $uploads['baseurl'] =  site_url('/wp-content');
    
    if (!file_exists($uploads['path'])) {
      mkdir($uploads['path'], 0755, true);
    }
    return $uploads;
}
add_filter('upload_dir', 'wp_set_custom_upload_folder');   

Rest everything should remain the same. I hope it will help you.

  • Related