WordPress: aggiungere alla Media Library un'immagine presente sul server

In questo articolo vedremo come aggiungere alla Media Library di WordPress un'immagine presente sul server.

WordPress di Gabriele Romanato

In questo articolo vedremo come aggiungere alla Media Library di WordPress un'immagine presente sul server.

La condizione di partenza è che l'immagine si trovi necessariamente sotto la directory wp-content/uploads.

function my_add_image_to_media_library( $filepath ) {
    $filename = basename( $filepath );
    $upload_file = wp_upload_bits( $filename, null, file_get_contents( $file ) );
    if( $upload_file['error'] ) {
        return 0;
    }
    $wp_filetype = wp_check_filetype( $filename, null );
    $wp_upload_dir = wp_upload_dir();
    $attachment = [
        'guid'           => $wp_upload_dir['url'] . '/' . $filename,
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', $filename ),
        'post_content' => '',
        'post_status' => 'inherit'
    ];
    $attach_id = wp_insert_attachment( $attachment, $file, 0 );
    if ( is_wp_error( $attach_id ) ) {
        return 0;
    }
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    return (int) $attach_id;
}

Il parametro $filepath dovrà contenere il percorso assoluto dell'immagine presente sul server.