Aggiungere immagini programmaticamente alla libreria media
Sto cercando di aggiungere programmaticamente più immagini alla libreria media, ho caricato le immagini in wp-content/uploads
, ora provo a utilizzare wp_insert_attachement
.
Ecco il codice, tuttavia non funziona come previsto, penso che i metadati non vengano generati correttamente, posso vedere i file nella libreria media, ma senza miniatura, inoltre se modifico l'immagine ottengo un errore che mi chiede di ricaricare l'immagine.
$filename_array = array(
'article1.jpg',
'article2.jpg',
);
// L'ID del post a cui è destinato questo allegato
$parent_post_id = 0;
// Ottieni il percorso della directory di upload
$wp_upload_dir = wp_upload_dir();
foreach ($filename_array as $filename) {
// Controlla il tipo di file. Lo useremo come 'post_mime_type'
$filetype = wp_check_filetype( basename( $filename ), null );
// Prepara un array di dati post per l'allegato
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Inserisci l'allegato
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Assicurati che questo file sia incluso, poiché wp_generate_attachment_metadata() ne dipende
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Genera i metadati per l'allegato e aggiorna il record del database
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}

$image_url = 'indirizzo img';
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file );
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 );

File scaricato ma nessuna miniatura disponibile, anche l'URL dell'allegato restituisce 404

@UmairHamid Anche a me. Questo perché il secondo argomento di wp_insert_attachment
dovrebbe essere il percorso del file (quindi $file
in questo esempio), non il nome del file. Ho modificato la risposta, in attesa di approvazione.

Usa wp_get_attachment_image_src
per ottenere l'URL, ad es. wp_get_attachment_image_src($attach_id)
- https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src

Se utilizzi la funzione di sideload di WordPress, puoi farlo più facilmente (e lasciare che WordPress gestisca tutta la sanificazione per te).
<?php
// esempio:
// $file = 'http://www.example.com/image.png';
// $description = 'alcuna descrizione';
function my_upload_image( $file, $description ) {
$file_array = [ 'name' => wp_basename( $file ), 'tmp_name' => download_url( $file ) ];
// Se c'è un errore nel salvataggio temporaneo, restituisce l'errore.
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return $file_array['tmp_name'];
}
// Esegue la validazione e il salvataggio.
$id = media_handle_sideload( $file_array, 0, $description );
// Se c'è un errore nel salvataggio permanente, elimina il file temporaneo.
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
}
return true;
}

Tieni presente che questo funziona solo all'interno di /wp-admin/
. Al di fuori di esso, devi assicurarti di includere questi tre file con require_once
:
ABSPATH . 'wp-admin/includes/file.php'
,
ABSPATH . 'wp-admin/includes/media.php'
,
ABSPATH . 'wp-admin/includes/image.php'

Questo funziona anche per immagini già memorizzate sul server, basta usare il percorso dell'immagine invece di download_url( $file )
. Ma se lo fai, tieni presente che quando usi media_handle_sideload
, l'immagine verrà automaticamente eliminata dopo l'elaborazione. Se non vuoi che ciò accada, puoi semplicemente copiare l'immagine nella directory tmp tramite $tmp_path = get_temp_dir() . basename( $file ); copy( $file, $tmp_path );
, quindi puoi usare 'tmp_name' => $tmp_path
invece.

Ho avuto problemi con la soluzione di @TrubinE dove i file immagine non venivano caricati correttamente.
Ecco un esempio completo che ha funzionato per me: https://gist.github.com/m1r0/f22d5237ee93bcccb0d9
Si tratta di un'idea simile ma che utilizza la libreria HTTP di WP per recuperare il contenuto invece di file_get_contents(). Ecco il contenuto della soluzione del gist github di m1r0:
if ( ! class_exists( 'WP_Http' ) ) {
include_once( ABSPATH . WPINC . '/class-http.php' );
}
$http = new WP_Http();
$response = $http->request( $meta['image_url'] );
if ( $response['response']['code'] !== 200 ) {
return false;
}
$upload = wp_upload_bits( basename( $meta['image_url'] ), null, $response['body'] );
if ( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id; codice qui

`<?php
// metodo più semplice per caricare un'immagine
$url_image = "http://example.com/any_image.jpg" ;
$new_image_id = upload_image_by_url ( $url_image );
function upload_image_by_url ($url) {
$title = basename($url) ;
$image_for_post_id = 0 ; // 0 significa che l'immagine non è associata a un post
$imgid = media_sideload_image( $url, $image_for_post_id, $title, 'id' );
if ( is_wp_error($imgid) ) {
echo "<br>Errore upload_image_by_url($url): ";
echo $imgid->get_error_message();
return false;
}
else {
echo "<br>upload_image_by_url($url) = $imgid";
return $imgid;
}
}?>`

Attualmente, la tua risposta non è chiara. Per favore, [modificala] per aggiungere dettagli aggiuntivi che aiuteranno gli altri a capire come questa affronta la domanda posta. Puoi trovare maggiori informazioni su come scrivere buone risposte nel centro assistenza.
