Home > Software design >  Woocommerce Product Creation Automation
Woocommerce Product Creation Automation

Time:10-07

I'm trying to develop a program that creates woocommerce products based on the media that were uploaded in the wordpress library.

All products have the same settings, the only things that change is the photo and the download.

With some research I managed to develop the following code that is running in functions.php:

add_action( 'init', 'product_automation');

function product_automation() {
  $loopProdutos = new WP_Query([
    'post_type' => 'product',
    'posts_per_page' => -1
  ]);
  $arrayProduct = (array) $loopProdutos->posts;
  // Picking up all the products from the store

  $idImgProduct = [];
  foreach($arrayProduct as $product) {
    $produto = wc_get_product($product->ID);
    $idImgProduct[] = $produto->image_id;
  }
  // Taking all photo IDs from existing products

  $loopImagens = new WP_Query([
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'orderby' => 'post_date',
    'order' => 'desc',
    'posts_per_page' => -1,
    'post_status' => 'inherit'
  ]);
  $arrayImg = (array) $loopImagens->posts;
  // Taking all uploaded photos

  $idImg = [];
  foreach($arrayImg as $image) {
    $idImg[] = $image->ID;
  }
  // Getting all uploaded photo IDs

  $newIds = array_diff($idImg, $idImgProduct);
  // Seeing which IDs do not yet exist

  $newProductsArray = [];
  // Array with new products

  foreach($newIds as $idImagem) {
    $objProduct = new WC_Product_Simple();
    $objProduct->set_name("Foto");
    $objProduct->set_status("publish"); 
    $objProduct->set_catalog_visibility('visible');
    $objProduct->set_price(15.00);
    $objProduct->set_regular_price(15.00);
    $objProduct->set_sold_individually(true);
    $objProduct->set_image_id($idImagem);
    $objProduct->set_downloadable(true);
    $objProduct->set_virtual(true);
    // Create a simple product
    
    $src_img  = wp_get_attachment_image_src( $idImagem, 'full');
    $img_meta = wp_get_attachment_metadata( $idImagem, false );
    
    $file_title = $img_meta['image_meta']['title'];
    $file_url   = reset($src_img);
    $file_md5   = md5($file_url);
    
    $download  = new WC_Product_Download();
    
    $download->set_name($file_title);
    $download->set_id($file_md5);
    $download->set_file($file_url);
    
    $downloads[$md5_num] = $download;
    
    $objProduct->set_downloads($downloads);
    // Code to automatically add download link to product

    $newProductsArray[] = $objProduct;
  }

  for ($i = 0; $i < count($newProductsArray); $i  ) {
    $newProductsArray[$i]->save();
  }
  //Loop to save each new product
}

The code works great. The problem is that it creates more products than anticipated.

For example, if I have 10 photos in my library, it creates 16 or 20 products (each photo generates more than one product).

I cannot find the error. Need help.

  • Related