Snippets

Garber GIT Añadir imágenes a producto WooCommerce

Created by Jesús Garcia
<?php

function gbiet_anyadir_imagen($producto_image_url, $producto_image_gallery_url, $product_id){
    //Le pasamos la id del producto y las url de la imagen para el producto y la galería
  
    $thumb_url = $producto_image_url;
    $thumb_url_gallery = $producto_image_gallery_url;
  
    // Descargamos el archivo temporal 
    $tmp = download_url( $thumb_url );
    $tmp_gallery = download_url( $thumb_url_gallery );
  
    //Creamos el array con los datos para la primera url, y de paso nos aseguramos que tenga un formato correcto
    preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url, $matches);//preg_match its for get sure image its correct
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;
  
    //Creamos el array con los datos para la segunda url
    preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url_gallery, $matches2);//preg_match its for get sure image its correct
    $file_array_gallery['name'] = basename($matches2[0]);
    $file_array_gallery['tmp_name'] = $tmp_gallery;
  
    //Creamos el objeto product con la id donde se asignará la imagen
    $product = newWC_Product_Variation($product_id);
  
    //Introducimos la imagen en el media de wordpress y guardamos su id en la variable thumbid
    $thumbid = media_handle_sideload( $file_array, $product_id, $product_id."-".$producto_image_url );//producto_image_url es la descripcion así podemos usarlo mejor
  
    //Y con esa id se la asignamos en su producto como imagen de cabecera
    set_post_thumbnail($product_id, $thumbid);
  
    //Con la imagen para la galería hacemos lo mismo y la añadimos en media
    $thumbid_gallery = media_handle_sideload( $file_array_gallery, $product_id, $producto_image_gallery_url );
  
    //Y la asignamos a la galería de ese producto
    update_post_meta( $product_id, '_product_image_gallery', $thumbid_gallery);
}

?>

Comments (1)

  1. Linda Melson
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.