如果您的图像命名为really 与产品SKU匹配并使用media uploader上载文件,您可以使用a single function 钩住add_attachment
你就完了。
一旦需要一些工作,我会避免在一个“会话”中上传所有数百张图片,也许你每次可以上传25/50张图片,而不会出现任何问题。。。
有关代码作用的更多信息,请参见注释:
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 );
}
});