WordPress: importare le immagini caricate tramite FTP nella Media Library

In WordPress possiamo importare le immagini caricate tramite FTP nella Media Library.

WordPress di Gabriele Romanato

In WordPress possiamo importare le immagini caricate tramite FTP nella Media Library.

La soluzione รจ la seguente:


function my_import_images() {
    $path = $_SERVER['DOCUMENT_ROOT'] . '/images';
    $scanned_directory = array_diff( scandir( $path ), array( '..', '.' ) );
    foreach ( $scanned_directory as $file ) {
        if ( preg_match( '/(jpe?g|png|gif|bmp)$/', $file ) ) {
            $filename = $path . '/' . $file;
            $upload_file = wp_upload_bits( basename( $filename ), null, file_get_contents( $filename ) );
            if ( !$upload_file['error'] ) {
                $wp_filetype = wp_check_filetype( basename( $filename ), null );
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_parent' => 0,
                    'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], 0 );
                if ( !is_wp_error( $attachment_id ) ) {
                    require_once( ABSPATH . 'wp-admin/includes/image.php' );
                    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
                    wp_update_attachment_metadata( $attachment_id, $attachment_data );
                }
            }
        }
    }

}

Commenti