admin管理员组

文章数量:1122846

I am currently uploading product photos directly to Wordpress via a Lightroom plugin (WP/LR Sync from Meowapps). The file names of the images also contain the article number in the form

arm-1001-01.jpg
arm-1001-02.jpg
arm-1001-03.jpg
arm-1001-04.jpg

arm-1002-01.jpg
arm-1002-02.jpg

arm-1003-01.jpg
arm-1003-02.jpg
arm-1003-03.jpg

Now the idea would be to use the following code to automatically assign the images to the products. The code works only for one image with exactly the filename/product sku matching. So how is it possible to get all the matching images for an product. Product 1 has sku "arm-1001", product 2 has sku "arm-1002" and so on.

    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 );
  }
});

本文标签: pluginsAutomatic assignment of multi images to products in WooCommerceWordpress with SKU