phpwordpressmedia-library

how make duplicate of an specific file in wordpress media library programatically


I programatically uploaded some files to wordpress media library by this function: media_handle_upload. this function after adding file to media library returns a number called wordpress_media_attachment_id . now I have some files in media library via their attachment ids.

now for some reasons, I want to make duplicate of them programatically.

That means I want to make a copy of those files with new attachment id.

now please give me a snippet code ?


Solution

  • finally solved my problem by this code:

    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $wp_upload_dir = wp_upload_dir();    
    $imgMeta = wp_get_attachment_metadata( $wordpress_media_attachment_id );
    $imgMime = $imgMeta['sizes']['thumbnail']['mime-type'];
    $absolutePath = "$wp_upload_dir[basedir]/$imgMeta[file]";
    
    $name = basename($imgMeta['file']);
    do{
        $rnd = mt_rand();
        $name2 = "_$rnd$name";
        $path2 = "$wp_upload_dir[path]/$name2";
    } while (file_exists($path2));
    @copy($absolutePath,$path2);
    
    $attachment = array(
            'guid'=> "$wp_upload_dir[url]/$name2", 
            'post_mime_type' => $imgMime,
            'post_title' => $name2,
            'post_content' => '',
            'post_status' => 'inherit'
    );
    $image_id = wp_insert_attachment($attachment, $path2);
    $attach_data = wp_generate_attachment_metadata( $image_id, $path2 );
    wp_update_attachment_metadata( $image_id, $attach_data );
    

    and finally I have a new duplicated file with new attachment id called $image_id