Skip to:
Content
Pages
Categories
Search
Top
Bottom

Upload avatar directly from the folder via PHP


  • Ivijan-Stefan Stipic
    Participant

    @ivijanstefan

    I have over 800 users for whom I have to upload a custom avatar. I have prepared a script that matches the username with the image name and all I have to do is call some BP function to set the avatar according to the user ID. How to do it and what function to use?

Viewing 2 replies - 1 through 2 (of 2 total)

  • shanebp
    Moderator

    @shanebp

    Take a look at buddypress\bp-core\bp-core-avatars.php
    Starting ~Line 920, * Handle avatar uploading.
    The ajax function shows how to apply user_id.


    Ivijan-Stefan Stipic
    Participant

    @ivijanstefan

    Thank you!

    Here is complete script for this:

    // Setup
    $path = 'some/folder/where/is/prepared/image.jpg'; // EXAMPLE
    $user_id = 123; // EXAMPLE
    $upload_path = bp_core_avatar_upload_path();
    $upload_dir = 'avatars';
    
    // Define filename and data
    $filename = pathinfo($path, PATHINFO_BASENAME);
    $data = file_get_contents( $path );
    
    // Prepare final destination
    $user_upload_dir = "${upload_path}/${upload_dir}/${user_id}";
    
    if( !is_dir( $user_upload_dir ) ) {
    	wp_mkdir_p( $user_upload_dir );
    	
    	if( !is_dir( $user_upload_dir ) ) {
    		return false;
    	}
    }
    
    // Prepare temp image
    $img = "${user_upload_dir}/{$filename}";
    $fc = file_put_contents( $img, $data );
    
    // Get size
    $image_size = getimagesize( $img );
    $width = $image_size[0];
    $height = $image_size[1];
    
    // Save avatar and assign to user
    $res = bp_attachments_create_item_type( 'avatar', [
    	'item_id'   => $user_id,
    	'object'    => 'user',
    	'component' => '',
    	'image'     => $img,
    	'crop_w'    => $width,
    	'crop_h'    => $height,
    	'crop_x'    => 0,
    	'crop_y'    => 0,
    ] );
    
    // Delete temp file
    wp_delete_file( $img );
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.
Skip to toolbar