Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/a03bb721e6941fe5c961e6529f006450 to your computer and use it in GitHub Desktop.
Save FrancoStino/a03bb721e6941fe5c961e6529f006450 to your computer and use it in GitHub Desktop.
Processes image URLs and YouTube iframe embeds from ACF fields during WordPress page creation via the REST API. It downloads, saves, and attaches images to the media library while extracting and storing YouTube URLs.

WordPress ACF Image and YouTube URL Uploads via REST API

Preview:
// Funzione per caricare l'immagine e ottenere l'ID dell'allegato
function uploadImageAndGetID( $img_url, $post_id, $name )
{
 // Carica i file necessari per la gestione degli allegati
 if ( !function_exists( 'wp_generate_attachment_metadata' ) )
 {
  require_once( ABSPATH . 'wp-admin/includes/image.php' );
 }
 if ( !function_exists( 'wp_handle_upload' ) )
 {
  require_once( ABSPATH . 'wp-admin/includes/file.php' );
 }

 // Download dell'immagine
 $image_data = file_get_contents( $img_url );

 if ( $image_data === false )
 {
  error_log( "Download fallito per URL: " . $img_url );
  return false;
 }

 // Gestione del nome file
 $extension = getExtension( $img_url );
 $filename  = sanitize_file_name( $name . '.' . $extension );

 // Percorso di upload
 $upload_dir  = wp_upload_dir();
 $upload_path = $upload_dir[ 'path' ] . '/' . $filename;

 // Salva il file
 $save_file = file_put_contents( $upload_path, $image_data );

 if ( $save_file === false )
 {
  error_log( "Salvataggio file fallito nel percorso: " . $upload_path );
  return false;
 }

 error_log( "File salvato con successo: " . $upload_path );

 // Prepara i dati per l'allegato
 $file_type  = wp_check_filetype( $filename, null );
 $attachment = [ 
  'post_mime_type' => $file_type[ 'type' ],
  'post_title'     => $filename,
  'post_content'   => '',
  'post_status'    => 'inherit',
  'post_parent'    => $post_id,
 ];

 // Inserisce l'allegato
 $attach_id = wp_insert_attachment( $attachment, $upload_path, $post_id );

 if ( is_wp_error( $attach_id ) )
 {
  error_log( "Errore WP nell'inserimento allegato: " . $attach_id->get_error_message() );
  return false;
 }

 error_log( "Allegato inserito con successo, ID: " . $attach_id );

 // Genera i metadati dell'allegato
 $attach_data = wp_generate_attachment_metadata( $attach_id, $upload_path );
 wp_update_attachment_metadata( $attach_id, $attach_data );

 error_log( "Metadati aggiornati per ID allegato: " . $attach_id );

 return $attach_id;
}


// Funzione per estrarre l'estensione
function getExtension( $filename ) {
    $filename = strtok( $filename, '?' );
    $path_info = pathinfo( $filename );
    return isset( $path_info['extension'] ) ? strtolower( $path_info['extension'] ) : 'jpg';
}

// Funzione per elaborare ricorsivamente i campi ACF
// Funzione per estrarre l'URL di YouTube da un iframe e pulirlo
function extractYoutubeUrl( $iframe_string )
{
 $pattern = '/src="([^"]+)"/';
 preg_match( $pattern, $iframe_string, $matches );

 if ( isset( $matches[ 1 ] ) )
 {
  // Estrai l'URL base rimuovendo tutti i parametri dopo il ?
  $url = preg_replace( '/\?.*/', '', $matches[ 1 ] );
  return $url;
 }

 return false;
}

// Modifica alla funzione processACFImagesUpload per gestire i campi video
function processACFImagesUpload( $data, $post_id )
{
 $updated_data = $data;

 foreach ( $data as $key => $value )
 {
  // Salta i campi specifici
  if ( $key === 'sizes' || $key === 'icon' )
  {
   continue;
  }

  // Controlla se il valore è un iframe di YouTube
  if ( is_string( $value ) && strpos( $value, '<iframe' ) !== false && strpos( $value, 'youtube.com' ) !== false )
  {
   $youtube_url = extractYoutubeUrl( $value );
   if ( $youtube_url )
   {
    $updated_data[ $key ] = $youtube_url;
    continue;
   }
  }

  // Gestione esistente per le immagini
  if ( is_string( $value ) && filter_var( $value, FILTER_VALIDATE_URL ) )
  {
   $path_info        = pathinfo( strtok( $value, '?' ) );
   $image_extensions = [ 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg' ];

   if ( isset( $path_info[ 'extension' ] ) && in_array( strtolower( $path_info[ 'extension' ] ), $image_extensions ) )
   {
    $filename      = sanitize_title( $path_info[ 'filename' ] ?: 'image' );
    $attachment_id = uploadImageAndGetID( $value, $post_id, $filename );

    if ( $attachment_id )
    {
     $updated_data[ $key ] = $attachment_id;
    }
   }
  }
  elseif ( is_array( $value ) )
  {
   $updated_data[ $key ] = processACFImagesUpload( $value, $post_id );
  }
 }

 return $updated_data;
}

// Hook per l'inserimento della pagina
add_action( 'rest_insert_page', function (\WP_Post $post, $request, $creating)
{
 $acf_data = $request->get_param( 'fields' );

 if ( is_array( $acf_data ) )
 {
  $updated_acf = processACFImagesUpload( $acf_data, $post->ID );

  foreach ( $updated_acf as $section_key => $section_value )
  {


   // Debug
   error_log( "Aggiornamento campo ACF: " . $section_key . " - Valore: " . $section_value );

   update_field( $section_key, $section_value, $post->ID );
  }
 }
}, 999999, 3 );

// Abilita le meta query nell'API REST
add_filter( 'rest_allow_meta_query', '__return_true' );
Associated Context
Type Code Snippet ( .php )
Associated Tags uploadImageAndGetID wp_generate_attachment_metadata wp_handle_upload wp_upload_dir wp_check_filetype sanitize_file_name file_get_contents error_log post_mime_type Framework: WordPress WordPress ACF REST API Image Upload Attachment Media Library YouTube Iframe PHP Web Development
💡 Smart Description This code snippet defines a function called "uploadImageAndGetID" that takes in an image URL, post ID, and name as parameters. It checks if the file is valid or does not exist on this directory (wp-admin/includes/image.php). If
Processes image URLs and YouTube iframe embeds from ACF fields during WordPress page creation via the REST API. It downloads, saves, and attaches images to the media library while extracting and storing YouTube URLs.
🔎 Suggested Searches PHP function to upload image and ID
How to generate attachment metadata in WordPress using wp_generate_attachment_metadata
Download fallito per URL with WP-admin/includes/file php
Code snippet for uploading file as a specific extension on an uploaded post
PHP code example for downloading dell'immagine
WordPress
ACF
REST API
Image Upload
YouTube
Iframe
Media Library
Attachment
wp_insert_attachment
wp_generate_attachment_metadata
Related Links https://www.geeksforgeeks.org/php-print_r-function/
https://www.geeksforgeeks.org/php-sessions/
https://www.geeksforgeeks.org/php-str_replace-function/
https://www.php.net/manual/en/function.file-put-contents.php
https://www.php.net/manual/en/function.session-set-save-handler.php
https://www.php.net/manual/en/function.file-get-contents.php
https://developer.wordpress.org/rest-api/
https://www.advancedcustomfields.com/resources/
Related People Davide Ladisa
Sensitive Information No Sensitive Information Detected
Shareable Link https://davideladisa.pieces.cloud/?p=2c17459819
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment