How to add product images using script?

You don’t need a plugin, if your images names really match with product SKUs and you use media uploader to upload the file, you can use a single function hooked in add_attachment and you are done.

Once it require some work, I’d avoid to upload all the hundreds of images in one “session”, probably you can upload sets of 25/50 images per time with no issues…

See comments for further informations on what code does:

add_action('add_attachment', function( $attachmentID ) {
  if ( ! class_exists( 'WC_Product' ) ) return; // if no WooCommerce do nothing

  // an attachment was jus saved, first of all get the file name
  $src = wp_get_attachment_image_src( $attachmentID, 'full' );
  $filename = pathinfo( $src[0], PATHINFO_FILENAME );

  // now let's see if exits a product with the sku that match filename
  $args = array(
    'meta_key' => '_sku',
    'meta_value' => $filename,
    'post_type' => 'product',
    'posts_per_page' => '1' // assuming sku is unique get only one post
  );
  $prods = get_posts( $args );
  if ( ! empty($prods) ) {

    // ok we have a match, exists a product having sku that match filename
    $product = array_pop( $prods );

    // set the thumbnail for the product
    set_post_thumbnail( $product, $attachmentID );

    // now "attach" the post to the product setting 'post_parent'
    $attachment = get_post( $attachmentID );
    $attachment->post_parent = $product->ID;
    wp_update_post( $attachment );
  }
});

Leave a Comment